SlideShare a Scribd company logo
0
1
Before we start learning let’s
Download
“Python” & “Pycharm”
2
Environment
Website: python.org/downloads/
3
For Mac OS
Environment
1. From Downloads file choose python-3.9.2 file
2. Click continue
3. Click agree.
4. Insert your password then click install.
4
For windows
Environment
5
Downloading PyCharm
code editor
The Python IDE Integrated development environment
Website:
https://www.jetbrains.com/pycharm/do
wnload/#section=mac
6
Download PyCharm (Cont.)
1. Click on “Download” 2. Choose “Community” edition click “Download.
7
Mac users
3. Go to downloads and click on
PyCharm folder.
4. Drag PyCharm icon to
Applications folder.
5. This window will appear because it is
downloaded from the internet.
8
Windows users
3. Click on the downloaded PyCharm folder then click “next”.
4. Click “next”.
5. Check the 64-bit launcher then press ”next”.
6. Click ”install”
9
Windows users
7. Click on “finish”.
8. Click “Accept”.
9. Check ”OK”.
10. Click ”Don’t send”
10
• Choose the first choice then click next , next, next and next again.
• Finally, this is the main page of PyCharm. Click on create new
project.
11
What are we going to learn in part 1?
• Basic programming terminologies.
• Writing comments.
• Variables, String Numbers.
• Data types: Integer, Float, String, Boolean.
• print function.
• Input function.
• Python conditional statements (If/elif/else statements) & Operators.
• Loops (for, Nested loop, while).
12
Basic Programming terms
• What is programming?
• Programming is using a code or source code, which is a sequence of
instructions to develop a program that will provide an output solution using
several tools such as a programming language & programming language
editor.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
13
Basic Programming terms (cont.)
• What is programming language?
• Programming language is a tool used to create a program by writing human
like language in a specific structure (syntax) using an editor that will translate
the human language to binary language of zeros and ones, which is the
computer language.
• syntax: The set of legal structures and commands that can be used in a particular
programming language.
• Types of programming languages:
• Open Source programming language:
• Python
• Paid Source
14
What is ?
• Python is an open source and cross-platform programming language
that has a general purpose used widely by developer's community to
create websites, games, machine learning modules and more.
• Why should you learn Python?
● Big Community
● General-purpose
● Open-source and cross-platform
● High productivity
● Memory safe
15
What is Python?
• High-level programming language.
• Invented in the Netherlands, early 90s by Guido van Rossum
• Named after Monty Python
• Open sourced from the beginning
• Increasingly popular
16
Why Python?
• Simple
• Python is a simple and minimalistic language in nature
• Reading a good python program should be like reading English
• Easy to Learn
• Cool documentation
• Free & Open source
• Freely distributed and Open source
• Maintained by the Python community
• High Level Language
• Portable
• The same code can run on Windows, Linux, MAC machines
Let’s Start programming with
17
18
Comments (Best Practice)
• Comments: notes of explanation within a program
• Ignored by Python interpreter
• Intended for a person reading the program’s code
• Begin with a # character
• Types of comments:
• Single Line Comments [ using # ]
• Multi-Line Comments """ type whatever here... """
• Example:
• Output:
# This line is a comment.
print("This line is not a comment, it is
code.")
This line is not a comment, it is code.
19
Variables
• Rules for naming variables in Python:
• Variable name cannot be a Python keyword
• Variable name cannot contain spaces
• First character must be a letter or an underscore
• After first character may use letters, digits, or underscores
• Variable names are case sensitive
• Variable name should reflect its use
• Variable: name that represents a
value stored in the computer
memory
• Used to access and manipulate
data stored in memory
• A variable references the value it
represents
• Assignment statement: used to
create a variable and make it
reference data
• Defining a variable:
• variable = expression
• Example:
age = 29
student_name= ’Maryam’
20
Variable Name Rules
1. Names cannot start with a number.
ex: 2made x
2. Names cannot contain spaces, use _ instead.
ex: two days x, and make it “two_days”
3. Names cannot start with symbols :’
",<>/?|()!@#$%^&*~-+ 4.
It's best practice to use names with lowercase.
21
Types of expressions that can be assigned
to a variable
 Float
 x = 3.56
 String (str)
 L = “Hello”
 Integer (int)
 Score_2 = 234
Boolean
 Pass_test = True OR False
22
print function
• Print function is used to give us the output of a variable stored value , or
print an input from the end-user or the developer of the program.
• For example:
• Variable stored value as output syntax:
x=3
y=5
result= x+y
print(result)
• Input from the developer syntax:
print(“Hello World”)
• Input from the end-user syntax:
name= input(‘What is your name? ‘)
print(‘Hi ‘+name)
23
print
• Print function used to display and print a line of output on the console
• Example:
print("Hello, world!")
print()
print("This program produces")
print("four lines of output")
• Its output:
Hello, world!
This program produces
four lines of output
24
Strings
• Strings (str)
• Must be enclosed in single (‘) or double (“) quote marks
• For example:
my_string = "This is a double-quoted string."
my_string = 'This is a single-quoted string.’
my_string= ‘ This is a “single-quoted” string.’
my_string= “ This is a ‘double-quoted’ string.”
double quotes to wrap single quotes
single quotes to wrap double quotes
25
Strings
• Example:
• Output:
message = "Hello Python World! "
print(message)
message = "Python is my favorite language! "
print(message)
Hello Python World!
Python is my favorite language!
26
String Concatenation
• String Concatenation: The + operator is used to concatenate strings
s = ‘Love’ + ‘Coding’
print(s) // LoveCoding
letter = ‘z-’
print(letter * 10) // z-z-z-z-z-z-z-z-z-z-
27
Built In string methods
1. Upper: Returns a copy of the string converted to uppercase
2. Lower: Returns a copy of the string converted to lowercase
3. Capitalize: Returns a copy of the string with only it’s first letter
capitalized
4. Split: It splits a string, and also allows you to split on any element of
the string
28
Strings
• String Functions
• len(string) - number of characters in a string
• str.lower(string) - lowercase version of a string
• str.upper(string) - uppercase version of a string
• str.isalpha(string) - True if the string has only alpha chars
• Many others: split, replace, find, format, etc.
• Note the “dot” notation: These are static methods.
29
Strings
• Example:
• Output:
s1= "Welcome to 500 course"
print(len(s1))
print(str.lower(s1))
print(str.upper(s1))
print(str.isalpha(s1))
21
welcome to 500 course
WELCOME TO 500 COURSE
False
30
Strings
• escape sequence: A sequence of characters used to represent certain
special characters in a string.
t tab character
n new line character
" quotation mark character
 backslash character
31
Strings
• Example:
• Output:
print("Hello everyone! ")
print("t Hello everyone! ")
print("Hello t everyone! ")
print("Hello n everyone! ")
Hello everyone!
Hello everyone!
Hello everyone!
Hello
everyone!
32
Numbers
• Numbers in Python can be in a form of:
• Integer (int) , for example:
age = 37
• Float, for example:
gpa = 3.67
• You can do all of the basic operations
with numbers.
• + for addition
• - for subtraction
• * for multiplication
• / for division
• ** for exponent
• () for parenthesis
print(3+4)
print(1.6-9.5)
print(2**2)
print(5.5/2)
result= 2+ 3*4
print(result)
result= (2+ 3)*4
print(result)
7
-7.9
4
2.75
14
20
33
Numbers
• A simple way to view the effect of an assignment is to assume that when
a variable changes, its old value is replaced
• You can change the value of a variable at any point.
x = 2
print(x)
x = 2.3
print(x)
2
Before
2.3
After
x x
34
Variables, Strings, and Numbers
• Dealing with simple numerical data is fairly straightforward in Python.
• There are different types of numbers: Integer and Float are most used.
• Integer like 3 , Float like 4.8
• You can do all of the basic operations with numbers.
• + for addition
• - for subtraction
• * for multiplication
• / for division
• ** for exponent
• () for parenthesis
• Higher precedence performed first
• Same precedence operators execute from left to right
35
Numbers
• Example:
• Calculate the following formula:
𝑎2
+ 𝑏3
× 𝑐
where a= 5, b=4, c=8
save the values in variables.
36
Assigning input
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?
• In Python, input is accomplished via an assignment statement combined
with a built-in function called input
• When Python encounters a call to input, it prints <prompt> (which is a
string literal) then pauses and waits for the user to type some text and
press the <Enter> key
37
Assigning input
• Here is a sample interaction with the Python interpreter:
• Example:
• Output:
• Notice that whatever the user types is then stored as a string
• What happens if the user inputs a number?
name= input("Enter your name ")
Enter your name Fatma
38
Assigning input
• In Python, the + operator can only concatenate strings as Python is
a strongly typed programming language.
• Example:
• Output:
Enter your favorite course name python
your favorite course name is python
name= input("Enter your favorite course name ")
print("your favorite course name is "+ name)
39
Assigning input
• we can convert the string output of the input function into an integer or
a float using the built-in int and float functions
• Example:
• Output
number= int(input("Enter a number "))
Enter a number 3 An integer
40
Assigning input
• We can convert the string output of the input function into an integer or
a float using the built-in int and float functions
• Example:
• Output
number= float(input("Enter a number "))
Enter a number 3.7 A float
41
Assigning input
• We can do various kinds of conversions between strings, integers and
floats using the built-in int, float, and str functions
integer  float
integer  string
string  float
string  integer
float  integer
float  string
x= 10
print(x)
print(float(x))
print(str(x))
y='20'
print(y)
print(float(y))
print(int (y))
z= 30.0
print(z)
print (int(z))
print (str(z))
30.0
30
30.0
20
20.0
20
10
10.0
10
42
If statement
Making Decisions – Controlling Program Flow
• To make interesting programs, you must be able to make decisions about data
and take different actions based upon those decisions.
• if statement: Executes a group of statements only if a certain condition is
true. Otherwise, the statements are skipped.
• Syntax of the If statement:
if condition:
Statement
Statement
• First line known as the if clause
• Includes the keyword “if” followed by “condition”
• The condition can be true or false
• When the if statement executes, the condition is tested, and if it is true the block statements are
executed. otherwise, block statements are skipped.
43
If statement
• Example:
• Output:
• The indented block of code following an if statement is executed if
the Boolean expression is true, otherwise it is skipped.
gpa = 3.4
if gpa > 2.0:
print ("Your application is accepted.”)
Your application is accepted.
44
if/else statements
• if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
• Example:
gpa = 1.4
if gpa > 2.0:
print("Welcome to University!")
else:
print("Your application is denied.")
print(“Good luck”)
45
If/ELIF/ELSE
• If you have several mutually exclusive choices, and want to guarantee that only
one of them is executed, you can use an IF/ELIF/ELSE statements. The ELIF
statement adds another boolean expression test and another block of code that
is executed if the boolean expression is true.
• Syntax:
if boolean expression :
STATEMENT
STATEMENT
elif 2nd boolean expression :
STATEMENT
STATEMENT
else:
STATEMENT
STATEMENT
46
If/ELIF/ELSE- Example
numberOfWheels = 3
if ( numberOfWheels == 1):
print “You are a Unicycle!”
elif (numberOfWheels == 2):
print “You are a Motorcycle!”
elif (numberOfWheels == 3):
print “You are a Tricycle!”
elif (numberOfWheels == 4):
print “You are a Car!”
else:
print “That's a LOT of wheels!”
• Only the print statement from the first true boolean expression is
executed.
47
Loops
• A loop statement allows us to execute a
statement or group of statements
multiple times.
• Two types of loops:
• for loop:
Executes a sequence of statements multiple
times and abbreviates the code that manages
the loop variable.
• while loop:
Repeats a statement or group of statements
while a given condition is TRUE. It tests the
condition before executing the loop body.
48
for Loop
• for loop: Repeats a set of statements over a group of values.
• Syntax:
• Example:
for < var > in range<sequence or group of valuse>:
<statements>
for i in range(5):
... print(i)
0
1
2
3
4
• Rules of loops:
• We indent the statements to be
repeated with tabs or spaces.
• VariableName gives a name to each
value, so you can refer to it in the
statements.
• GroupOfValues can be a range of
integers, specified with the range
function.
49
for
• Example:
• Output:
• Example:
• Output:
for x in (1 , 5):
print(x," Hello")
1 Hello
5 Hello
for x in range(1 , 5):
print(x," Hello")
1 Hello
2 Hello
3 Hello
4 Hello
50
for
• Example:
• Output:
n = 100
sum = 0
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until 100:”, sum)
Sum of 1 until 100: 5050
51
Nested Loop
• Loops defined within another loop is called Nested loop. When an outer loop contains an inner loop
in its body it is called Nested looping.
• Syntax:
for <expression>:
for <expression>:
body
• for example:
Stops summing at 4
because it is grater than
5 and does not count 5
as an output
2+1 =3
3+1=4
4+1=5 it will give
output 4 and
ends the output
result as 4
for a in range (1,5):
for b in range (1,a+1):
print(a)
52
while
• while loop: Executes a group of statements as long as a condition is
True.
• good for indefinite loops (repeat an unknown number of times)
• Syntax:
while condition:
statements
• Example: Output:
number = 1
while number < 200:
print (number)
number = number * 2
1
2
4
8
16
32
64
128
53
Let’s review
what we’ve learned
so far!
54
Review
1. Which of the following are legal python identifiers (circle your answers).
a) hello
b) 5times
c) int
d) Pepper2
e) iden_tifier
f) APPLES
g) if
h) _1xyz
55
Review
1. Which of the following are legal python identifiers (circle your answers).
a) hello
b) 5times
c) int
d) Pepper2
e) iden_tifier
f) APPLES
g) if
h) _1xyz
56
Review
2. Which of the following mark the beginning of a comment?
a) //
b) /*
c) /**
d) #
3. Select all option(s) that print Python-is-very-easy
a) print(“Python‟, “is‟, “very‟, “easy”)
b) b) print(“Python‟, “is‟, “very‟, “easy‟ + “-‟ * 4 c)
c) print(“Python-‟ + “is - very - easy‟)
d) d) print(“Python‟ + “-‟ + “is‟ + “-‟ + “very‟ + “-‟ + “easy‟)
57
Review
2. Which of the following mark the beginning of a comment?
a) //
b) /*
c) /**
d) #
3. Select all option(s) that print Python-is-very-easy
a) print(“Python‟, “is‟, “very‟, “easy”)
b) print(“Python‟, “is‟, “very‟, “easy‟ + “-‟ * 4 c)
c) print(“Python-‟ + “is - very - easy‟)
d) print(“Python‟ + “-‟ + “is‟ + “-‟ + “very‟ + “-‟ + “easy‟)
58
Review
4. What gets printed when Python execute that program
x ='5’
y = 2
z = x+y
Print(z)
a) 52
b) 7
c) Syntax Error
d) z
59
Review
4. What gets printed when Python execute that program
x ='5’
y = 2
z = x+y
Print(z)
a) 52
b) 7
c) Syntax Error
d) z
60
Review
7. Write a Python program that can take four float numbers from the
console/ user and displays their average.
61
Review
7. Write a Python program that reads four float numbers from the
console and displays their average.
x= float(input (" Enter first number"))
y= float(input (" Enter second number"))
z= float(input (" Enter third number"))
w= float(input (" Enter fourth number"))
av= (x+y+z+w)/4
print("The aveage is ", av)
62
Exercise
Write a Python program that reads two numbers and determines the following:
If two numbers are equal, then it will print first number = second number
If the first number is greater than the second number, it will print first number > second number
If the first number is less than the second number, it will print first number < second number
Sample output 1:
Enter the first number:
3
Enter the second number:
5
3 < 5
Sample output 2:
Enter the first number:
7
Enter the second number:
7
7 = 7
63
Exercise Solution
x=int(input("Enter the first number: "))
y=int(input("Enter the second number: "))
if (x==y):
print (x," = ", y)
elif (x<y):
print(x," < ", y)
else:
print(x," > ", y)
Contact info
• Maryam AlMahdi
• E-mail: mariam.almahdi@outlook.com
• Instagram: @gdgkwt_maryam
64
65
Now let’s continue
Python basics part 2
with Eng. Mahdi AlFaraj
What are we going to learn?
• Functions
• Global and local variables
• Python Lists, Tuples, Sets, Dictionaries
• Python Arrays
• Python Try… Except
• Object-oriented programming
• Python Classes/Objects
• Modules and modules’ methods
66
Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
Creating a function syntax:
Calling a function:
• To call a function, use the function name followed by parenthesis:
67
Functions
Function Arguments:
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
Example:
def my_function(fname):
print(fname + " Johnson")
my_function("Emil")
my_function("Tobias")
my_function("Linus") 68
Functions
Return Values:
• To let a function return a value, use the return statement:
69
Functions
Example:
def bar(x) :
return x * x
print(bar(3))
Output:
9
• Note that the function bar takes
one parameter and returns the
square of the x value inputted.
70
Global and local variables
• A global variable is a variable declared outside of a function
• Scope: this variable can be used in the entire program
• A local variable is a variable declared inside of a function.
• Scope: this variable is used only in the function it is declared in.
71
Global and local variables
• Will this code work?
Yes it will work!!
72
Global and local variables
• We can use the global key word if we want to change a global variable
inside a function.
• Will this code work?
Yes it will work!!
73
Lists:
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.
• Lists are created using square brackets and each item is separated by
a comma.
• Examples of Lists:
my_list = [1,2,3]
my_list = [‘strings’, 1, 2, 3.9, True, [1,2,3] ]
print(len(my_list))
List can contain
numbers, strings,
nested lists, etc.
The len() function will tell you how many
items are in the sequence of your list
Python Lists, Tuples, Sets, Dictionaries
74
• A list or array is a sequence of items where the entire sequence is
referred to by a single name (i.e. s) and individual items can be selected
by indexing (i.e. s[i]). The first item in the list has an index of 0.
• Python lists are dynamic. They can grow and shrink on demand.
• In other programming languages, arrays are generally a fixed size,
meaning that when you create the array, you have to specify how many
items it can hold.
• Python lists are heterogeneous, a single list can hold arbitrary data
types.
• Arrays are generally homogeneous, meaning they can hold only one data
type.
Python Lists, Tuples, Sets, Dictionaries
75
List Positive and Negative Indices:
t = [23, ‘abc’, 4.56, 3, ‘def’]
Positive index: count from the left, starting with 0
print(t[1])
‘abc’
Negative index: count from right, starting with –1
Print(t[-3])
4.56
Python Lists, Tuples, Sets, Dictionaries
76
List Operations:
Python Lists, Tuples, Sets, Dictionaries
77
• List Concatenation:
my_list = ['one’, 'two’]
my_list = my_list + ['new item’]
print(my_list) // [‘one’, ‘two’, ‘new item’]
• Replicating a list:
my_list = ['1', '2'] *2
print(my_list) // ['1', '2', '1', '2']
Python Lists, Tuples, Sets, Dictionaries
78
List Operations (Slicing)
Python List Slicing Syntax:
Python Lists, Tuples, Sets, Dictionaries
79
List Operations (Slicing)
Examples:
t = [23, ‘abc’, 4.56, 3, ‘def’]
Returns copy of list with subset of original members. Start copying at first
index, and stop copying before the second index
print t[1:4]
[‘abc’, 4.56, 3]
You can also use negative indices
print t[1:-1]
[‘abc’, 4.56, 3]
Python Lists, Tuples, Sets, Dictionaries
80
List Operations (Slicing)
Examples:
t = [23, ‘abc’, 4.56, 3, ‘def’]
Omit first index to make a copy starting from the beginning of list
print(t[:2])
[23, ‘abc’]
Omit second index to make a copy starting at 1st index and going to end of the
list
print(t[2:])
[4.56, 3, ‘def’]
Python Lists, Tuples, Sets, Dictionaries
81
List Operations (Copying the whole list)
• [ : ] makes a copy of an entire sequence
print(t[:])
[23, ‘abc’, 4.56, 3, ‘def’]
Python Lists, Tuples, Sets, Dictionaries
82
List Operations ( “in” Operator)
• Boolean test whether a value is inside a list:
t = [1, 2, 4, 5]
print(3 in t)
False
print(4 in t)
True
• For strings, tests for substrings
a = 'abcde’
print('c' in a)
True
'cd' in a
True
Print('ac' in a)
False
• Careful: the in keyword is also used in the syntax of for loops and list
comprehensions
Python Lists, Tuples, Sets, Dictionaries
83
• Example
Code:
• Output:
S1 = ['yellow', 'red', 'blue', 'green', 'black’]
S2=[1, 2, 3]
print (S1)
Print(S1+S2)
print (S1[0])
print (S2*3)
print (len(S1))
print (S1[0:2])
Print( 1 in S2)
['yellow', 'red', 'blue', 'green', 'black']
['yellow', 'red', 'blue', 'green', 'black’,1,2,3]
yellow
[1, 2, 3, 1, 2, 3, 1, 2, 3]
5
[‘yellow', ‘red’]
True
Python Lists, Tuples, Sets, Dictionaries
84
• Example
Code:
• Output:
S = ['yellow', 'red', 'blue', 'green', 'black']
print (S[-1])
S[2]='silver'
print(S[:])
black
['yellow', 'red', 'silver', 'green', 'black’]
Python Lists, Tuples, Sets, Dictionaries
85
List Functions:
Python Lists, Tuples, Sets, Dictionaries
86
List Functions:
• len(ex_list): number of elements in list (top level).
• min(ex_list): smallest element. Must all be the same type!
• max(ex_list): largest element, again all must be the same type
• sum(ex_list): sum of the elements, numeric only
Python Lists, Tuples, Sets, Dictionaries
87
• List Functions Examples:
• Output:
C = ['A', 'B', 'C', 'D']
print (C.index('C'))
2
C = ['C', 'B', 'A', 'D’]
print (len(C))
4
C = ['A', 'B', 'C', 'D’]
print (C.count(‘A’))
D = ['A', 'B', ‘A', ‘D’]
print (D.count(‘A’))
1
2
Python Lists, Tuples, Sets, Dictionaries
88
• List Functions Examples:
• Output:
[ 'B', 'C', 'D','A']
C = ['A', 'B', 'C', ‘D’, ‘A’]
C.remove('A’)
print (C)
C = ['C', 'B', 'A', 'D']
C.sort()
print (C)
['A', 'B', 'C', 'D']
C = ['A', 'B', 'C', 'D']
C.reverse()
print (C)
['D', 'C', 'B', 'A']
Python Lists, Tuples, Sets, Dictionaries
89
• List Functions Examples:
• Output:
C = ['A', 'B', 'C', 'D']
C.append ('X')
print (C)
['A', 'B', 'C', 'D', 'X’]
C = ['A', 'B', 'C', 'D']
V = ['Z','Y','Q']
C.extend (V)
print (C)
['A', 'B', 'C', 'D', 'Z', 'Y', 'Q']
C = ['A', 'B', 'C', 'D']
V = [‘X','Y',’Z']
C.insert (1,'K')
print (C)
C.insert (0,V)
print (C)
C.insert (0, [‘J',’I',’M’])
print (C)
['A', 'K', 'B', 'C', 'D’]
[[‘X', 'Y', ‘Z'], 'A', 'K', 'B', 'C', 'D’]
[[‘J', ‘I', ‘M'], ['Z', 'Y', 'Q'],'A','K', 'B', 'C', 'D']
Python Lists, Tuples, Sets, Dictionaries
90
• List Functions Examples:
• Output:
E = [1, 3, 5, 7, 9]
print (min(E))
1
E = [1, 3, 5, 7, 9]
print (max(E))
9 25
E = [1, 3, 5, 7, 9]
print (sum(E))
E = [1, 3, 1, 7, 9]
print (E.count(1))
print (E.count(8))
2
0
Python Lists, Tuples, Sets, Dictionaries
91
Tuples:
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are indexed: the first item has index [0], the second item
has index [1] etc.
Example:
Python Lists, Tuples, Sets, Dictionaries
92
Sets:
• A set is a collection which is both unordered and unindexed.
• Unordered: Set items can appear in a different order every time you
use them, and cannot be referred to by index or key.
• Set items are unordered, unchangeable, and do not allow duplicate
values.
• Sets are written with curly brackets.
Python Lists, Tuples, Sets, Dictionaries
93
Sets:
Example (running same code twice):
Output 1: Output 2:
Python Lists, Tuples, Sets, Dictionaries
94
Dictionaries:
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered (Python 3.7+), changeable
and does not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values:
Python Lists, Tuples, Sets, Dictionaries
95
• Python offers built-in data types for storing collection of data such as
Lists, Tuples, Sets etc.
• However, there is a module called array that allows us to use arrays to
store a collection of numeric values of same numeric data type.
• Lists are much more flexible than arrays. They can store elements of
different data types including strings. And, if you need to do
mathematical computation on arrays and matrices, you are much
better off using something like NumPy.
Python Arrays
96
• When an error occurs, or exception as we call it, Python will normally
stop and generate an error message.
• These exceptions can be handled using the try statement.
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• Example (variable x is never defined):
Python Try… Except
97
• We can define as many exception blocks as we want.
• Example: if you want to execute a special block of code for a special
kind of error:
Python Try… Except
98
• Python common built-in Exceptions Hierarchy:
Python Try… Except
99
• Real use scenario:
try:
f = open("demofile.txt")
f.write("New user: Alex")
f.close()
except:
print("Something went wrong when writing to the file")
Python Try… Except
100
Object-Oriented Programming
• Object-oriented programming (OOP) is a method of structuring a program
by bundling related properties and behaviors into individual objects.
• For instance, an object could represent a person with properties like a
name, age, and address and behaviors such as walking, talking, breathing,
and running. Or it could represent an email with properties like a recipient
list, subject, and body and behaviors like adding attachments and sending.
• Put another way, object-oriented programming is an approach for
modeling concrete, real-world things, like cars, as well as relations between
things, like companies and employees, students and teachers, and so on.
OOP models real-world entities as software objects that have some data
associated with them and can perform certain functions. 101
Python Classes & Objects
• Python is an object-oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
• A Class is like an object constructor, or a "blueprint" for creating
objects
102
Python Classes & Objects
• To understand the meaning of classes we have to understand the
built-in __init__() function.
• All classes have a function called __init__(), which is always executed
when the class is being initiated.
• Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created.
103
Python Classes & Objects
Example: Create a class named Person, use the __init__() function to
assign values for name and age:
104
Python Classes & Objects
• Objects can also contain methods. Methods in objects are functions
that belong to the object.
Example: Insert a function that prints a greeting, and execute it on the
p1 object.
105
Python Classes & Objects
• The self parameter is a reference to the current instance of the class,
and is used to access variables that belongs to the class.
• You can modify properties of objects like this:
• You can delete properties of an object, or the object itself entirely by
using the del keyword:
106
Python Classes & Objects
Exercise:
Create a class named "Car" with the following 3 attributes: brand, color, price. The class
should have a function for printing out the object's details. Create a new object and call
the function to print the values assigned.
Hint: Remember the format for creating a class:
class Car:
def __init__(self, brand, color, price):
self.brand = brand
…
…
Finished early? Add a line of code for modifying the color of the car object being added to
YELLOW.
107
Python Classes & Objects
Exercise Solution:
Modification for color
108
Python Classes & Objects
Exercise Solution Output:
Exercise Solution Output with Modification:
109
Modules & Modules’ methods
What is a module?
• Consider a module to be the same as a code library.
• A file containing a set of functions you want to include in your application.
• The highest-level structure of Python
• Each file with the .py suffix is a module
• Each module has its own namespace
• Example of syntax:
• import mymodule Brings all elements of mymodule in, but must refer to as
mymodule.
• Examples of common Modules:
Math Module Turtle Module Pandas Module
Random Module Matplotlib Module 110
Modules & Modules’ methods
Example for creating and using a module:
• To create a module just save the code you want in a file with the file
extension .py:
• We can now use the module we just created by using the import
statement:
111
Thank you!
GDG Kuwait would like to thank you for attending today’s
workshop and wishes you all the best in your learning
journey!
112
References
• https://www.w3schools.com/python/
• Python Cheat Sheet by Mosh Hamedani
• Ms. Fatimah Al-Rashed – Python lab
113

More Related Content

What's hot

Python programming
Python programmingPython programming
Python programming
Ganesh Bhosale
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
raksharao
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
myrajendra
 
Python Basics
Python BasicsPython Basics
Python Basics
primeteacher32
 
Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
Jussi Pohjolainen
 
Python training
Python trainingPython training
Python training
Kunalchauhan76
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
myrajendra
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
Python programming
Python programmingPython programming
Python programming
Prof. Dr. K. Adisesha
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
Sasidhar Kothuru
 
Python_in_Detail
Python_in_DetailPython_in_Detail
Python_in_Detail
MAHALAKSHMI P
 

What's hot (20)

Python programming
Python programmingPython programming
Python programming
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
 
Python training
Python trainingPython training
Python training
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
 
Java introduction
Java introductionJava introduction
Java introduction
 
Python ppt
Python pptPython ppt
Python ppt
 
Data file handling
Data file handlingData file handling
Data file handling
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Python programming
Python programmingPython programming
Python programming
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Python_in_Detail
Python_in_DetailPython_in_Detail
Python_in_Detail
 

Similar to #Code2Create: Python Basics

Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1
Elaf A.Saeed
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
chandankumar943868
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Python Intro
Python IntroPython Intro
Python Intro
koppenolski
 
Cs4hs2008 track a-programming
Cs4hs2008 track a-programmingCs4hs2008 track a-programming
Cs4hs2008 track a-programming
Rashi Agarwal
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
TamalSengupta8
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
Punithavel Ramani
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris2
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
Arpittripathi45
 
Demo learn python
Demo learn pythonDemo learn python
Demo learn python
DIT University, Dehradun
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
gmadhu8
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
Python
PythonPython
Python
Shivam Gupta
 

Similar to #Code2Create: Python Basics (20)

Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python Intro
Python IntroPython Intro
Python Intro
 
Cs4hs2008 track a-programming
Cs4hs2008 track a-programmingCs4hs2008 track a-programming
Cs4hs2008 track a-programming
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Demo learn python
Demo learn pythonDemo learn python
Demo learn python
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python
PythonPython
Python
 

More from GDGKuwaitGoogleDevel

معسكر أساسيات البرمجة في لغة بايثون.pdf
معسكر أساسيات البرمجة في لغة بايثون.pdfمعسكر أساسيات البرمجة في لغة بايثون.pdf
معسكر أساسيات البرمجة في لغة بايثون.pdf
GDGKuwaitGoogleDevel
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
i/o extended: Intro to <UX> Design
i/o extended: Intro to <UX> Design  i/o extended: Intro to <UX> Design
i/o extended: Intro to <UX> Design
GDGKuwaitGoogleDevel
 
#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart
GDGKuwaitGoogleDevel
 
Building arcade game using python workshop
 Building arcade game using python workshop Building arcade game using python workshop
Building arcade game using python workshop
GDGKuwaitGoogleDevel
 
Wordpress website development workshop by Seham Abdlnaeem
Wordpress website development workshop by Seham AbdlnaeemWordpress website development workshop by Seham Abdlnaeem
Wordpress website development workshop by Seham Abdlnaeem
GDGKuwaitGoogleDevel
 
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMerajWTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
GDGKuwaitGoogleDevel
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020 - Building (Progressive) Web Apps
DevFest Kuwait 2020 - Building (Progressive) Web AppsDevFest Kuwait 2020 - Building (Progressive) Web Apps
DevFest Kuwait 2020 - Building (Progressive) Web Apps
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google CloudDevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
GDGKuwaitGoogleDevel
 
DevFest Kuwait 2020 - GDG Kuwait
DevFest Kuwait 2020 - GDG KuwaitDevFest Kuwait 2020 - GDG Kuwait
DevFest Kuwait 2020 - GDG Kuwait
GDGKuwaitGoogleDevel
 

More from GDGKuwaitGoogleDevel (11)

معسكر أساسيات البرمجة في لغة بايثون.pdf
معسكر أساسيات البرمجة في لغة بايثون.pdfمعسكر أساسيات البرمجة في لغة بايثون.pdf
معسكر أساسيات البرمجة في لغة بايثون.pdf
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
i/o extended: Intro to <UX> Design
i/o extended: Intro to <UX> Design  i/o extended: Intro to <UX> Design
i/o extended: Intro to <UX> Design
 
#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart
 
Building arcade game using python workshop
 Building arcade game using python workshop Building arcade game using python workshop
Building arcade game using python workshop
 
Wordpress website development workshop by Seham Abdlnaeem
Wordpress website development workshop by Seham AbdlnaeemWordpress website development workshop by Seham Abdlnaeem
Wordpress website development workshop by Seham Abdlnaeem
 
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMerajWTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
WTM/IWD 202: Introduction to digital accessibility by Dr. Zainab AlMeraj
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
 
DevFest Kuwait 2020 - Building (Progressive) Web Apps
DevFest Kuwait 2020 - Building (Progressive) Web AppsDevFest Kuwait 2020 - Building (Progressive) Web Apps
DevFest Kuwait 2020 - Building (Progressive) Web Apps
 
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google CloudDevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
DevFest Kuwait 2020- Cloud Study Jam: Kubernetes on Google Cloud
 
DevFest Kuwait 2020 - GDG Kuwait
DevFest Kuwait 2020 - GDG KuwaitDevFest Kuwait 2020 - GDG Kuwait
DevFest Kuwait 2020 - GDG Kuwait
 

Recently uploaded

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 

Recently uploaded (20)

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 

#Code2Create: Python Basics

  • 1. 0
  • 2. 1 Before we start learning let’s Download “Python” & “Pycharm”
  • 4. 3 For Mac OS Environment 1. From Downloads file choose python-3.9.2 file 2. Click continue 3. Click agree. 4. Insert your password then click install.
  • 6. 5 Downloading PyCharm code editor The Python IDE Integrated development environment Website: https://www.jetbrains.com/pycharm/do wnload/#section=mac
  • 7. 6 Download PyCharm (Cont.) 1. Click on “Download” 2. Choose “Community” edition click “Download.
  • 8. 7 Mac users 3. Go to downloads and click on PyCharm folder. 4. Drag PyCharm icon to Applications folder. 5. This window will appear because it is downloaded from the internet.
  • 9. 8 Windows users 3. Click on the downloaded PyCharm folder then click “next”. 4. Click “next”. 5. Check the 64-bit launcher then press ”next”. 6. Click ”install”
  • 10. 9 Windows users 7. Click on “finish”. 8. Click “Accept”. 9. Check ”OK”. 10. Click ”Don’t send”
  • 11. 10 • Choose the first choice then click next , next, next and next again. • Finally, this is the main page of PyCharm. Click on create new project.
  • 12. 11 What are we going to learn in part 1? • Basic programming terminologies. • Writing comments. • Variables, String Numbers. • Data types: Integer, Float, String, Boolean. • print function. • Input function. • Python conditional statements (If/elif/else statements) & Operators. • Loops (for, Nested loop, while).
  • 13. 12 Basic Programming terms • What is programming? • Programming is using a code or source code, which is a sequence of instructions to develop a program that will provide an output solution using several tools such as a programming language & programming language editor. • output: The messages printed to the user by a program. • console: The text box onto which output is printed.
  • 14. 13 Basic Programming terms (cont.) • What is programming language? • Programming language is a tool used to create a program by writing human like language in a specific structure (syntax) using an editor that will translate the human language to binary language of zeros and ones, which is the computer language. • syntax: The set of legal structures and commands that can be used in a particular programming language. • Types of programming languages: • Open Source programming language: • Python • Paid Source
  • 15. 14 What is ? • Python is an open source and cross-platform programming language that has a general purpose used widely by developer's community to create websites, games, machine learning modules and more. • Why should you learn Python? ● Big Community ● General-purpose ● Open-source and cross-platform ● High productivity ● Memory safe
  • 16. 15 What is Python? • High-level programming language. • Invented in the Netherlands, early 90s by Guido van Rossum • Named after Monty Python • Open sourced from the beginning • Increasingly popular
  • 17. 16 Why Python? • Simple • Python is a simple and minimalistic language in nature • Reading a good python program should be like reading English • Easy to Learn • Cool documentation • Free & Open source • Freely distributed and Open source • Maintained by the Python community • High Level Language • Portable • The same code can run on Windows, Linux, MAC machines
  • 19. 18 Comments (Best Practice) • Comments: notes of explanation within a program • Ignored by Python interpreter • Intended for a person reading the program’s code • Begin with a # character • Types of comments: • Single Line Comments [ using # ] • Multi-Line Comments """ type whatever here... """ • Example: • Output: # This line is a comment. print("This line is not a comment, it is code.") This line is not a comment, it is code.
  • 20. 19 Variables • Rules for naming variables in Python: • Variable name cannot be a Python keyword • Variable name cannot contain spaces • First character must be a letter or an underscore • After first character may use letters, digits, or underscores • Variable names are case sensitive • Variable name should reflect its use • Variable: name that represents a value stored in the computer memory • Used to access and manipulate data stored in memory • A variable references the value it represents • Assignment statement: used to create a variable and make it reference data • Defining a variable: • variable = expression • Example: age = 29 student_name= ’Maryam’
  • 21. 20 Variable Name Rules 1. Names cannot start with a number. ex: 2made x 2. Names cannot contain spaces, use _ instead. ex: two days x, and make it “two_days” 3. Names cannot start with symbols :’ ",<>/?|()!@#$%^&*~-+ 4. It's best practice to use names with lowercase.
  • 22. 21 Types of expressions that can be assigned to a variable  Float  x = 3.56  String (str)  L = “Hello”  Integer (int)  Score_2 = 234 Boolean  Pass_test = True OR False
  • 23. 22 print function • Print function is used to give us the output of a variable stored value , or print an input from the end-user or the developer of the program. • For example: • Variable stored value as output syntax: x=3 y=5 result= x+y print(result) • Input from the developer syntax: print(“Hello World”) • Input from the end-user syntax: name= input(‘What is your name? ‘) print(‘Hi ‘+name)
  • 24. 23 print • Print function used to display and print a line of output on the console • Example: print("Hello, world!") print() print("This program produces") print("four lines of output") • Its output: Hello, world! This program produces four lines of output
  • 25. 24 Strings • Strings (str) • Must be enclosed in single (‘) or double (“) quote marks • For example: my_string = "This is a double-quoted string." my_string = 'This is a single-quoted string.’ my_string= ‘ This is a “single-quoted” string.’ my_string= “ This is a ‘double-quoted’ string.” double quotes to wrap single quotes single quotes to wrap double quotes
  • 26. 25 Strings • Example: • Output: message = "Hello Python World! " print(message) message = "Python is my favorite language! " print(message) Hello Python World! Python is my favorite language!
  • 27. 26 String Concatenation • String Concatenation: The + operator is used to concatenate strings s = ‘Love’ + ‘Coding’ print(s) // LoveCoding letter = ‘z-’ print(letter * 10) // z-z-z-z-z-z-z-z-z-z-
  • 28. 27 Built In string methods 1. Upper: Returns a copy of the string converted to uppercase 2. Lower: Returns a copy of the string converted to lowercase 3. Capitalize: Returns a copy of the string with only it’s first letter capitalized 4. Split: It splits a string, and also allows you to split on any element of the string
  • 29. 28 Strings • String Functions • len(string) - number of characters in a string • str.lower(string) - lowercase version of a string • str.upper(string) - uppercase version of a string • str.isalpha(string) - True if the string has only alpha chars • Many others: split, replace, find, format, etc. • Note the “dot” notation: These are static methods.
  • 30. 29 Strings • Example: • Output: s1= "Welcome to 500 course" print(len(s1)) print(str.lower(s1)) print(str.upper(s1)) print(str.isalpha(s1)) 21 welcome to 500 course WELCOME TO 500 COURSE False
  • 31. 30 Strings • escape sequence: A sequence of characters used to represent certain special characters in a string. t tab character n new line character " quotation mark character backslash character
  • 32. 31 Strings • Example: • Output: print("Hello everyone! ") print("t Hello everyone! ") print("Hello t everyone! ") print("Hello n everyone! ") Hello everyone! Hello everyone! Hello everyone! Hello everyone!
  • 33. 32 Numbers • Numbers in Python can be in a form of: • Integer (int) , for example: age = 37 • Float, for example: gpa = 3.67 • You can do all of the basic operations with numbers. • + for addition • - for subtraction • * for multiplication • / for division • ** for exponent • () for parenthesis print(3+4) print(1.6-9.5) print(2**2) print(5.5/2) result= 2+ 3*4 print(result) result= (2+ 3)*4 print(result) 7 -7.9 4 2.75 14 20
  • 34. 33 Numbers • A simple way to view the effect of an assignment is to assume that when a variable changes, its old value is replaced • You can change the value of a variable at any point. x = 2 print(x) x = 2.3 print(x) 2 Before 2.3 After x x
  • 35. 34 Variables, Strings, and Numbers • Dealing with simple numerical data is fairly straightforward in Python. • There are different types of numbers: Integer and Float are most used. • Integer like 3 , Float like 4.8 • You can do all of the basic operations with numbers. • + for addition • - for subtraction • * for multiplication • / for division • ** for exponent • () for parenthesis • Higher precedence performed first • Same precedence operators execute from left to right
  • 36. 35 Numbers • Example: • Calculate the following formula: 𝑎2 + 𝑏3 × 𝑐 where a= 5, b=4, c=8 save the values in variables.
  • 37. 36 Assigning input • So far, we have been using values specified by programmers and printed or assigned to variables • How can we let users (not programmers) input values? • In Python, input is accomplished via an assignment statement combined with a built-in function called input • When Python encounters a call to input, it prints <prompt> (which is a string literal) then pauses and waits for the user to type some text and press the <Enter> key
  • 38. 37 Assigning input • Here is a sample interaction with the Python interpreter: • Example: • Output: • Notice that whatever the user types is then stored as a string • What happens if the user inputs a number? name= input("Enter your name ") Enter your name Fatma
  • 39. 38 Assigning input • In Python, the + operator can only concatenate strings as Python is a strongly typed programming language. • Example: • Output: Enter your favorite course name python your favorite course name is python name= input("Enter your favorite course name ") print("your favorite course name is "+ name)
  • 40. 39 Assigning input • we can convert the string output of the input function into an integer or a float using the built-in int and float functions • Example: • Output number= int(input("Enter a number ")) Enter a number 3 An integer
  • 41. 40 Assigning input • We can convert the string output of the input function into an integer or a float using the built-in int and float functions • Example: • Output number= float(input("Enter a number ")) Enter a number 3.7 A float
  • 42. 41 Assigning input • We can do various kinds of conversions between strings, integers and floats using the built-in int, float, and str functions integer  float integer  string string  float string  integer float  integer float  string x= 10 print(x) print(float(x)) print(str(x)) y='20' print(y) print(float(y)) print(int (y)) z= 30.0 print(z) print (int(z)) print (str(z)) 30.0 30 30.0 20 20.0 20 10 10.0 10
  • 43. 42 If statement Making Decisions – Controlling Program Flow • To make interesting programs, you must be able to make decisions about data and take different actions based upon those decisions. • if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped. • Syntax of the If statement: if condition: Statement Statement • First line known as the if clause • Includes the keyword “if” followed by “condition” • The condition can be true or false • When the if statement executes, the condition is tested, and if it is true the block statements are executed. otherwise, block statements are skipped.
  • 44. 43 If statement • Example: • Output: • The indented block of code following an if statement is executed if the Boolean expression is true, otherwise it is skipped. gpa = 3.4 if gpa > 2.0: print ("Your application is accepted.”) Your application is accepted.
  • 45. 44 if/else statements • if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False. • Example: gpa = 1.4 if gpa > 2.0: print("Welcome to University!") else: print("Your application is denied.") print(“Good luck”)
  • 46. 45 If/ELIF/ELSE • If you have several mutually exclusive choices, and want to guarantee that only one of them is executed, you can use an IF/ELIF/ELSE statements. The ELIF statement adds another boolean expression test and another block of code that is executed if the boolean expression is true. • Syntax: if boolean expression : STATEMENT STATEMENT elif 2nd boolean expression : STATEMENT STATEMENT else: STATEMENT STATEMENT
  • 47. 46 If/ELIF/ELSE- Example numberOfWheels = 3 if ( numberOfWheels == 1): print “You are a Unicycle!” elif (numberOfWheels == 2): print “You are a Motorcycle!” elif (numberOfWheels == 3): print “You are a Tricycle!” elif (numberOfWheels == 4): print “You are a Car!” else: print “That's a LOT of wheels!” • Only the print statement from the first true boolean expression is executed.
  • 48. 47 Loops • A loop statement allows us to execute a statement or group of statements multiple times. • Two types of loops: • for loop: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. • while loop: Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
  • 49. 48 for Loop • for loop: Repeats a set of statements over a group of values. • Syntax: • Example: for < var > in range<sequence or group of valuse>: <statements> for i in range(5): ... print(i) 0 1 2 3 4 • Rules of loops: • We indent the statements to be repeated with tabs or spaces. • VariableName gives a name to each value, so you can refer to it in the statements. • GroupOfValues can be a range of integers, specified with the range function.
  • 50. 49 for • Example: • Output: • Example: • Output: for x in (1 , 5): print(x," Hello") 1 Hello 5 Hello for x in range(1 , 5): print(x," Hello") 1 Hello 2 Hello 3 Hello 4 Hello
  • 51. 50 for • Example: • Output: n = 100 sum = 0 for counter in range(1,n+1): sum = sum + counter print("Sum of 1 until 100:”, sum) Sum of 1 until 100: 5050
  • 52. 51 Nested Loop • Loops defined within another loop is called Nested loop. When an outer loop contains an inner loop in its body it is called Nested looping. • Syntax: for <expression>: for <expression>: body • for example: Stops summing at 4 because it is grater than 5 and does not count 5 as an output 2+1 =3 3+1=4 4+1=5 it will give output 4 and ends the output result as 4 for a in range (1,5): for b in range (1,a+1): print(a)
  • 53. 52 while • while loop: Executes a group of statements as long as a condition is True. • good for indefinite loops (repeat an unknown number of times) • Syntax: while condition: statements • Example: Output: number = 1 while number < 200: print (number) number = number * 2 1 2 4 8 16 32 64 128
  • 55. 54 Review 1. Which of the following are legal python identifiers (circle your answers). a) hello b) 5times c) int d) Pepper2 e) iden_tifier f) APPLES g) if h) _1xyz
  • 56. 55 Review 1. Which of the following are legal python identifiers (circle your answers). a) hello b) 5times c) int d) Pepper2 e) iden_tifier f) APPLES g) if h) _1xyz
  • 57. 56 Review 2. Which of the following mark the beginning of a comment? a) // b) /* c) /** d) # 3. Select all option(s) that print Python-is-very-easy a) print(“Python‟, “is‟, “very‟, “easy”) b) b) print(“Python‟, “is‟, “very‟, “easy‟ + “-‟ * 4 c) c) print(“Python-‟ + “is - very - easy‟) d) d) print(“Python‟ + “-‟ + “is‟ + “-‟ + “very‟ + “-‟ + “easy‟)
  • 58. 57 Review 2. Which of the following mark the beginning of a comment? a) // b) /* c) /** d) # 3. Select all option(s) that print Python-is-very-easy a) print(“Python‟, “is‟, “very‟, “easy”) b) print(“Python‟, “is‟, “very‟, “easy‟ + “-‟ * 4 c) c) print(“Python-‟ + “is - very - easy‟) d) print(“Python‟ + “-‟ + “is‟ + “-‟ + “very‟ + “-‟ + “easy‟)
  • 59. 58 Review 4. What gets printed when Python execute that program x ='5’ y = 2 z = x+y Print(z) a) 52 b) 7 c) Syntax Error d) z
  • 60. 59 Review 4. What gets printed when Python execute that program x ='5’ y = 2 z = x+y Print(z) a) 52 b) 7 c) Syntax Error d) z
  • 61. 60 Review 7. Write a Python program that can take four float numbers from the console/ user and displays their average.
  • 62. 61 Review 7. Write a Python program that reads four float numbers from the console and displays their average. x= float(input (" Enter first number")) y= float(input (" Enter second number")) z= float(input (" Enter third number")) w= float(input (" Enter fourth number")) av= (x+y+z+w)/4 print("The aveage is ", av)
  • 63. 62 Exercise Write a Python program that reads two numbers and determines the following: If two numbers are equal, then it will print first number = second number If the first number is greater than the second number, it will print first number > second number If the first number is less than the second number, it will print first number < second number Sample output 1: Enter the first number: 3 Enter the second number: 5 3 < 5 Sample output 2: Enter the first number: 7 Enter the second number: 7 7 = 7
  • 64. 63 Exercise Solution x=int(input("Enter the first number: ")) y=int(input("Enter the second number: ")) if (x==y): print (x," = ", y) elif (x<y): print(x," < ", y) else: print(x," > ", y)
  • 65. Contact info • Maryam AlMahdi • E-mail: mariam.almahdi@outlook.com • Instagram: @gdgkwt_maryam 64
  • 66. 65 Now let’s continue Python basics part 2 with Eng. Mahdi AlFaraj
  • 67. What are we going to learn? • Functions • Global and local variables • Python Lists, Tuples, Sets, Dictionaries • Python Arrays • Python Try… Except • Object-oriented programming • Python Classes/Objects • Modules and modules’ methods 66
  • 68. Functions • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. • A function can return data as a result. Creating a function syntax: Calling a function: • To call a function, use the function name followed by parenthesis: 67
  • 69. Functions Function Arguments: • Information can be passed into functions as arguments. • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. Example: def my_function(fname): print(fname + " Johnson") my_function("Emil") my_function("Tobias") my_function("Linus") 68
  • 70. Functions Return Values: • To let a function return a value, use the return statement: 69
  • 71. Functions Example: def bar(x) : return x * x print(bar(3)) Output: 9 • Note that the function bar takes one parameter and returns the square of the x value inputted. 70
  • 72. Global and local variables • A global variable is a variable declared outside of a function • Scope: this variable can be used in the entire program • A local variable is a variable declared inside of a function. • Scope: this variable is used only in the function it is declared in. 71
  • 73. Global and local variables • Will this code work? Yes it will work!! 72
  • 74. Global and local variables • We can use the global key word if we want to change a global variable inside a function. • Will this code work? Yes it will work!! 73
  • 75. Lists: • Lists are used to store multiple items in a single variable. • Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. • Lists are created using square brackets and each item is separated by a comma. • Examples of Lists: my_list = [1,2,3] my_list = [‘strings’, 1, 2, 3.9, True, [1,2,3] ] print(len(my_list)) List can contain numbers, strings, nested lists, etc. The len() function will tell you how many items are in the sequence of your list Python Lists, Tuples, Sets, Dictionaries 74
  • 76. • A list or array is a sequence of items where the entire sequence is referred to by a single name (i.e. s) and individual items can be selected by indexing (i.e. s[i]). The first item in the list has an index of 0. • Python lists are dynamic. They can grow and shrink on demand. • In other programming languages, arrays are generally a fixed size, meaning that when you create the array, you have to specify how many items it can hold. • Python lists are heterogeneous, a single list can hold arbitrary data types. • Arrays are generally homogeneous, meaning they can hold only one data type. Python Lists, Tuples, Sets, Dictionaries 75
  • 77. List Positive and Negative Indices: t = [23, ‘abc’, 4.56, 3, ‘def’] Positive index: count from the left, starting with 0 print(t[1]) ‘abc’ Negative index: count from right, starting with –1 Print(t[-3]) 4.56 Python Lists, Tuples, Sets, Dictionaries 76
  • 78. List Operations: Python Lists, Tuples, Sets, Dictionaries 77
  • 79. • List Concatenation: my_list = ['one’, 'two’] my_list = my_list + ['new item’] print(my_list) // [‘one’, ‘two’, ‘new item’] • Replicating a list: my_list = ['1', '2'] *2 print(my_list) // ['1', '2', '1', '2'] Python Lists, Tuples, Sets, Dictionaries 78
  • 80. List Operations (Slicing) Python List Slicing Syntax: Python Lists, Tuples, Sets, Dictionaries 79
  • 81. List Operations (Slicing) Examples: t = [23, ‘abc’, 4.56, 3, ‘def’] Returns copy of list with subset of original members. Start copying at first index, and stop copying before the second index print t[1:4] [‘abc’, 4.56, 3] You can also use negative indices print t[1:-1] [‘abc’, 4.56, 3] Python Lists, Tuples, Sets, Dictionaries 80
  • 82. List Operations (Slicing) Examples: t = [23, ‘abc’, 4.56, 3, ‘def’] Omit first index to make a copy starting from the beginning of list print(t[:2]) [23, ‘abc’] Omit second index to make a copy starting at 1st index and going to end of the list print(t[2:]) [4.56, 3, ‘def’] Python Lists, Tuples, Sets, Dictionaries 81
  • 83. List Operations (Copying the whole list) • [ : ] makes a copy of an entire sequence print(t[:]) [23, ‘abc’, 4.56, 3, ‘def’] Python Lists, Tuples, Sets, Dictionaries 82
  • 84. List Operations ( “in” Operator) • Boolean test whether a value is inside a list: t = [1, 2, 4, 5] print(3 in t) False print(4 in t) True • For strings, tests for substrings a = 'abcde’ print('c' in a) True 'cd' in a True Print('ac' in a) False • Careful: the in keyword is also used in the syntax of for loops and list comprehensions Python Lists, Tuples, Sets, Dictionaries 83
  • 85. • Example Code: • Output: S1 = ['yellow', 'red', 'blue', 'green', 'black’] S2=[1, 2, 3] print (S1) Print(S1+S2) print (S1[0]) print (S2*3) print (len(S1)) print (S1[0:2]) Print( 1 in S2) ['yellow', 'red', 'blue', 'green', 'black'] ['yellow', 'red', 'blue', 'green', 'black’,1,2,3] yellow [1, 2, 3, 1, 2, 3, 1, 2, 3] 5 [‘yellow', ‘red’] True Python Lists, Tuples, Sets, Dictionaries 84
  • 86. • Example Code: • Output: S = ['yellow', 'red', 'blue', 'green', 'black'] print (S[-1]) S[2]='silver' print(S[:]) black ['yellow', 'red', 'silver', 'green', 'black’] Python Lists, Tuples, Sets, Dictionaries 85
  • 87. List Functions: Python Lists, Tuples, Sets, Dictionaries 86
  • 88. List Functions: • len(ex_list): number of elements in list (top level). • min(ex_list): smallest element. Must all be the same type! • max(ex_list): largest element, again all must be the same type • sum(ex_list): sum of the elements, numeric only Python Lists, Tuples, Sets, Dictionaries 87
  • 89. • List Functions Examples: • Output: C = ['A', 'B', 'C', 'D'] print (C.index('C')) 2 C = ['C', 'B', 'A', 'D’] print (len(C)) 4 C = ['A', 'B', 'C', 'D’] print (C.count(‘A’)) D = ['A', 'B', ‘A', ‘D’] print (D.count(‘A’)) 1 2 Python Lists, Tuples, Sets, Dictionaries 88
  • 90. • List Functions Examples: • Output: [ 'B', 'C', 'D','A'] C = ['A', 'B', 'C', ‘D’, ‘A’] C.remove('A’) print (C) C = ['C', 'B', 'A', 'D'] C.sort() print (C) ['A', 'B', 'C', 'D'] C = ['A', 'B', 'C', 'D'] C.reverse() print (C) ['D', 'C', 'B', 'A'] Python Lists, Tuples, Sets, Dictionaries 89
  • 91. • List Functions Examples: • Output: C = ['A', 'B', 'C', 'D'] C.append ('X') print (C) ['A', 'B', 'C', 'D', 'X’] C = ['A', 'B', 'C', 'D'] V = ['Z','Y','Q'] C.extend (V) print (C) ['A', 'B', 'C', 'D', 'Z', 'Y', 'Q'] C = ['A', 'B', 'C', 'D'] V = [‘X','Y',’Z'] C.insert (1,'K') print (C) C.insert (0,V) print (C) C.insert (0, [‘J',’I',’M’]) print (C) ['A', 'K', 'B', 'C', 'D’] [[‘X', 'Y', ‘Z'], 'A', 'K', 'B', 'C', 'D’] [[‘J', ‘I', ‘M'], ['Z', 'Y', 'Q'],'A','K', 'B', 'C', 'D'] Python Lists, Tuples, Sets, Dictionaries 90
  • 92. • List Functions Examples: • Output: E = [1, 3, 5, 7, 9] print (min(E)) 1 E = [1, 3, 5, 7, 9] print (max(E)) 9 25 E = [1, 3, 5, 7, 9] print (sum(E)) E = [1, 3, 1, 7, 9] print (E.count(1)) print (E.count(8)) 2 0 Python Lists, Tuples, Sets, Dictionaries 91
  • 93. Tuples: • A tuple is a collection which is ordered and unchangeable. • Tuples are written with round brackets. • Tuple items are indexed: the first item has index [0], the second item has index [1] etc. Example: Python Lists, Tuples, Sets, Dictionaries 92
  • 94. Sets: • A set is a collection which is both unordered and unindexed. • Unordered: Set items can appear in a different order every time you use them, and cannot be referred to by index or key. • Set items are unordered, unchangeable, and do not allow duplicate values. • Sets are written with curly brackets. Python Lists, Tuples, Sets, Dictionaries 93
  • 95. Sets: Example (running same code twice): Output 1: Output 2: Python Lists, Tuples, Sets, Dictionaries 94
  • 96. Dictionaries: • Dictionaries are used to store data values in key:value pairs. • A dictionary is a collection which is ordered (Python 3.7+), changeable and does not allow duplicates. • Dictionaries are written with curly brackets, and have keys and values: Python Lists, Tuples, Sets, Dictionaries 95
  • 97. • Python offers built-in data types for storing collection of data such as Lists, Tuples, Sets etc. • However, there is a module called array that allows us to use arrays to store a collection of numeric values of same numeric data type. • Lists are much more flexible than arrays. They can store elements of different data types including strings. And, if you need to do mathematical computation on arrays and matrices, you are much better off using something like NumPy. Python Arrays 96
  • 98. • When an error occurs, or exception as we call it, Python will normally stop and generate an error message. • These exceptions can be handled using the try statement. • The try block lets you test a block of code for errors. • The except block lets you handle the error. • Example (variable x is never defined): Python Try… Except 97
  • 99. • We can define as many exception blocks as we want. • Example: if you want to execute a special block of code for a special kind of error: Python Try… Except 98
  • 100. • Python common built-in Exceptions Hierarchy: Python Try… Except 99
  • 101. • Real use scenario: try: f = open("demofile.txt") f.write("New user: Alex") f.close() except: print("Something went wrong when writing to the file") Python Try… Except 100
  • 102. Object-Oriented Programming • Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. • For instance, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending. • Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees, students and teachers, and so on. OOP models real-world entities as software objects that have some data associated with them and can perform certain functions. 101
  • 103. Python Classes & Objects • Python is an object-oriented programming language. • Almost everything in Python is an object, with its properties and methods. • A Class is like an object constructor, or a "blueprint" for creating objects 102
  • 104. Python Classes & Objects • To understand the meaning of classes we have to understand the built-in __init__() function. • All classes have a function called __init__(), which is always executed when the class is being initiated. • Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created. 103
  • 105. Python Classes & Objects Example: Create a class named Person, use the __init__() function to assign values for name and age: 104
  • 106. Python Classes & Objects • Objects can also contain methods. Methods in objects are functions that belong to the object. Example: Insert a function that prints a greeting, and execute it on the p1 object. 105
  • 107. Python Classes & Objects • The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. • You can modify properties of objects like this: • You can delete properties of an object, or the object itself entirely by using the del keyword: 106
  • 108. Python Classes & Objects Exercise: Create a class named "Car" with the following 3 attributes: brand, color, price. The class should have a function for printing out the object's details. Create a new object and call the function to print the values assigned. Hint: Remember the format for creating a class: class Car: def __init__(self, brand, color, price): self.brand = brand … … Finished early? Add a line of code for modifying the color of the car object being added to YELLOW. 107
  • 109. Python Classes & Objects Exercise Solution: Modification for color 108
  • 110. Python Classes & Objects Exercise Solution Output: Exercise Solution Output with Modification: 109
  • 111. Modules & Modules’ methods What is a module? • Consider a module to be the same as a code library. • A file containing a set of functions you want to include in your application. • The highest-level structure of Python • Each file with the .py suffix is a module • Each module has its own namespace • Example of syntax: • import mymodule Brings all elements of mymodule in, but must refer to as mymodule. • Examples of common Modules: Math Module Turtle Module Pandas Module Random Module Matplotlib Module 110
  • 112. Modules & Modules’ methods Example for creating and using a module: • To create a module just save the code you want in a file with the file extension .py: • We can now use the module we just created by using the import statement: 111
  • 113. Thank you! GDG Kuwait would like to thank you for attending today’s workshop and wishes you all the best in your learning journey! 112
  • 114. References • https://www.w3schools.com/python/ • Python Cheat Sheet by Mosh Hamedani • Ms. Fatimah Al-Rashed – Python lab 113