Chapter 2. Python Basics
Chapter 2. Python Basics
Python Basics
Python
Chapter Content
• 1. Keywords
• 2. Variables - Constants
• 3. Operators - Expression
• 4. Statements - Statement Block - Comments
• 5. Simple Data types
• 6. Structured Data Types
• 7. Control flow statements
• 8. Loop control statements
• 9. Functions
• 10. File Handling
• 11. Exception Handling
Python 2
1. Keywords
• Not use keyword to name for: class, object, function, variable, const…
Python 3
2. Variables - Constants
• Rules for variable name in Python:
• Must start with a letter or the underscore character
• Cannot start with a number
• Can only contain alpha, numeric characters and underscores (A-z, 0-9,
and _ )
• Don't use Python's keyword to name variables
• Are case-sensitive (age, Age and AGE are three different variables)
Python 4
2. Variables - Constants
• Example:
• Correct variable name: Hello_1 _Hello
• Variables are different : spam Spam SPAM
• Incorrect variable name:
• 1_Hello: start with a number character
• He llo: contains spaces
• print: Python's keyword
Python 5
2. Variables - Constants
• Python has no command for declaring a variable.
• Assignment operator: =
• Multiple data types can be assigned to a variable
x = 4 # x is of type int
x = "Sally" # x is now of type str
• Variables can also specific to the particular data type with casting
Python 6
2. Variables - Constants
• One values can be assigned to multiple variables
a, b, c = 1
Python 7
2. Variables - Constants
• Constant is a quantity with constant value
a, b, c = 1
Constants
Python 8
3. Operators - Expression
• Arithmetic Operators: +, -, *, /, %, **, //
• Comparison Operators: ==, !=, >=, <=, >, <
• Logical Operators: and, or, not
• Identity Operators: is, is not
• Membership Operators: in, not in
• Bitwise Operators: &, |, ^, ~, >>, <<
• Assignment Operators: =, +=, -=, *=, /=, %=, **=, //=,
|=, &=, >>=, <<=
Python 9
3. Operators - Expression
• An expression is used to calculate and return a value
• An expression consisting of a sequence of operands (values) linked by
operators
• Ví dụ:
• 3 + 2 + 6 11
• "Python is a" + Programming language" Python is a
Programming language
• (3 + 4) * 2 – (2 + 3) / 5 14
Python 10
4. Statement - Command Block - Comments
• End of a statement on line break
• A statement can be extended over multiple lines by character (\)
• Example: sum = 1+3+5 + \
sum = 1+3+5+3+2+4
3+2+4
• Or ( ); [ ] ; { }
• Example: The commands below are the same
sum = {1+3+5 + sum = (1+3+5 +
3+2+4} 3+2+4)
Python 12
4. Statement - Command Block - Comments
• Comments for a line starts with a #, and Python will ignore them
# This is a comment
print("Hello, World!")
"""
# This is a comment This is a comment
# written in written in
# more than just one line more than just one line
print("Hello, World!") """
print("Hello, World!")
Python 13
5. Simple Data types: Numeric Types
• int (integer) is a whole number, positive or negative, without decimals,
of unlimited length
• float is a number, positive or negative, containing one or more decimals.
It can also be scientific numbers with an "e" to indicate the power of 10.
• complex numbers are written with a "j" as the imaginary part.
x = 1 # int
y = 2.8 # float
z = 1j # complex
• Convert from one type to another with the int(), float() and complex()
methods
Python 14
5. Simple Data types: Numeric Types
• To uses the following symbols to perform operations on numeric data:
• + : Addition
• - : Subtraction
• / : Division. When two integers (int) are divided, the result is a real number (float)
• * : Multiplication
• **: Exponential
• % : Remainder Division
• // : Integer division
• Example:
5 + 2 7 5 – 2 3 5 // 2 2
5 * 2 10 5 / 2 2.5 5 ** 2 25
5 % 2 1
Python 15
5. Simple Data types: Numeric Types
• The precedence’s order of operations according to PPMAL ruler
Parenthesis x = 1 + 2 ** 3 / 4 * 5
print(x) 11.0
Power
1 + 2 ** 3 / 4 * 5
Multiplication
1 + 8 / 4 * 5
Addition
1 + 2 * 5
Left to Right
1 + 10
11
Python 16
5. Simple Data types: Numeric Types
• Some common Math Functions
• Import functions of math class: from math import *
Function Name Describe Example Result
ceil(float value) Round up ceil(102.4) 103
cos(radian value) Cosin of an angle cos(0) 1
floor(float value) Round down floor(102.4) 102
log(value, base) logarit with base log(6,2) 2.6
log10(value) logarit with base 10 log10(6) =log(6,10) 0.78
max(value 1,value 2 ...) Return value maximum max(3,5,6) 6
min(value 1, value 2, ...) Return value minimum min(3,5,6) 3
round(float value) Rounding round(102.4) 102
round(102.7) 103
sin(gradian value) Sin of an angle sin(0) 0
sqrt(value) Calculate square root 2 sqrt(25) 5
abs(value) Return the absolute value abs(-100) 100
pi = 3.141592653589793 e = 2.718281828459045
Python 17
5. Simple Data types: String Type
• Data string is surrounded by either single quotation marks, or double
quotation marks
• Example: 'hello' is the same as "hello"
• Assign a multiline string to a variable by using three quotes.
longer = " " " This string has
multiple lines " " "
Python 18
5. Simple Data types: String Type
• String operators str1= “Hello” str2= “world”
Python 19
5. Simple Data types: String Type
• String Functions
Python 20
5. Simple Data types: String Type
• Access to string’s character: StringName[index]
• Index value is a integer number and first element is 0
• The index value of the last element can be represented by the value -1
• Index value can be the value of the expression
fruit = “banana”
letter_5 = fruit[5]
b a n a n a print(letter_5) a
0 1 2 3 4 5 letter_end = fruit[-1]
print(letter_end) a
x = 3
w = fruit[x - 1]
print(w) n
Python 21
5. Simple Data types: String Type
• Extract substring: StringName[index 1: index 2]
• Extract the substring, starting at the character with "index 1" to the
adjacent preceding character of the character with "index 2“
Value b a n a n a
Index
0 1 2 3 4 5
fruit = 'banana'
letter = fruit[1:3]
print(letter) an
Python 22
5. Simple Data types: String Type
• Extract the substring, starting from the first character to the immediately
preceding character of the specified character with "index":
StringName[: index]
• Extract the substring, starting at the character with "index" to the last
character: StringName[index:]
fruit = 'banana'
• Get the whole string : StringName[:] letter = fruit[:3]
print(letter) ban
Value b a n a n a letter = fruit[1:]
Index 0 1 2 3 4 5 print(letter) anana
letter = fruit[:]
print(letter) banana
Python 23
5. Simple Data types: String Type
Value M o n t y P y t h o n
Index 0 1 2 3 4 5 6 7 8 9 10 11
s = "Monty python"
print(s[:2]) Mo
print(s[8:]) thon
print(s[:]) Monty Python
print(s[0:4]) Mont
print(s[6:7]) P
print(s[6:20]) Python
Python 24
5. Simple Data types: String Type
• Method: is an action that Python can perform on an object. Syntax to use
the method: ObjectName.MethodName()
• Some methods for string data:
• StringName.title(): convert the data of StringNmae to data with the first
character of the words in the string to uppercase.
• StringName.upper(): Convert data to uppercase string.
• StringName.lower(): convert data to lowercase string.
• Example:
name= "ngon ngu python"
print(name.title()) Ngon Ngu Python
print(name.upper()) NGON NGU PYTHON
print(name.lower()) ngon ngu python
Python 25
5. Simple Data types: String Type
• Some methods for string data:
• StringName.rstrip(): Remove the spaces on the right of the string
• StringName.lstrip(): Remove the spaces on the left of the string
• StringName.strip(): Remove spaces on both sides of the string.
• Example:
name = " Tran "
print(name.lstrip()) "Tran "
print(name.rstrip()) Tran"
print(name.strip()) "Tran"
Python 26
5. Simple Data types: String Type
• Some methods for string data:
• StringName.replace(SubStr 1, Subtr 2): Generates a new string from
StringName. This new string is replaced by SubStr 1 with SubStr 2.
• Example:
name = "HelloPython2.0"
nameNew = name.replace("2.0", "3.7.14")
print(nameNew) "HelloPython3.7.14"
• StringName.find(string to find): Return a Integer number which the index of
String to find. If not found, return -1. Starting position is index 0.
• Example:
name = "HelloPanana"
print(name.find("na")) 8
print(name.find("Python")) -1
Python 27
5. Simple Data types: String Type
• Some methods for string data:
• StringName.find(string to find, location): Return a Integer number which the
index of String to find. If not found, return -1. Starting position is index
location.
• Example:
name = "HelloPananaPanana" 12
print(name.find("",6))
print(name.find("")) 5
Python 28
5. Simple Data types: String Type
• Some methods for string data:
• StringName.isupper(): Return True, if all character is Uppercase character.
• StringName.islower(): Return True, if all character is Lowercase character.
• Example:
Python 29
5. Simple Data types: String Type
• Some methods for string data:
• Concatenating: Use the symbol (+)
• Example:
Ten = "trung"
Ho_lot = "van"
Ho = "phan"
Ho_va_ten = Ho + "" + Ho_lot + ""+ Ten
print(Ho_va_ten) "phanvantrung"
• Repeat number of times string value: Use the symbol ( * )
• Example:
st="Hello"
st = 4 * st
print(st) HelloHelloHelloHello
Python 30
5. Simple Data types: String Type
• Some methods for string data:
• Use the symbol (in) to check if a string is in another string
• Example:
st1 = "Hello Python"
st2 = "Hello"
st3 = "Pyth"
st2 in st1 True
st3 in st1 True
• Use the symbol (\n) to insert a newline into the string
• Example: print("Xin\nChao!") Xin
Chao!
• Use the symbol (\t) to insert a Tab
• Example: print("Xin\tChao!") Xin Chao!
Python 31
5. Simple Data types: String Type
• Some Functions for string data:
• len(StringName): Returns an integer indicating the length of the string.
• Example:
name = " Tran "
print(len(name)) 7
• int(IntegerStringName): Convert string to an integer number
• float(FloatStringName): Convert string to an float number
• Example:
st1, st2 = "20", "30"
Sum1 = st1 + st2 "2030"
Sum2 = int(st1) + int(st2) 50
st1, st2 ="20.5", "30.5"
Sum1 = st1 + st2 "20.530.5"
Sum2 = float(st1) + float(st2) 51.0
Python 32
5. Simple Data types: Boolean Type
Python 33
5. Simple Data types: Boolean Type
34
Python 34
5. Simple Data types: Boolean Type
and True and True True (2 < 3) and (-1 < 5) True
True and False False (2 == 3) and (-1 < 5) False
False and False False (2 == 3) and (-1 > 5) False
or True or False True (2 == 3) or (-1 < 5) True
not Not True False not (2 == 3) True
Not False True
Python 35
Practice and exercises
Part 1
Python 36
6. Structured Data Types
• Lists
• Sets
• Tuples
• Dictionary
Python 37
6. Structured Data Types: Lists
• are like dynamically sized arrays used to store multiple items
• Items are separated by commas and enclosed in square brackets
• Properties of a list: mutable, ordered, heterogeneous, duplicates.
Python 38
6. Structured Data Types: List Initialization
• Using square brackets []
# an empty list • Using list multiplication
L1= list[] # a list of 10 items of ' '
# a list of 3 items
L2= list['banana','apple', 'kiwi'] L1= list[' ']*10
Python 39
6. Structured Data Types: Operations on Lists
• Access
• Update
• Modify
• Insert
• Append
• Extend
• Remove
• Sort
Python 40
6. Structured Data Types: Operations on Lists
• Access:
• can access to List items by referring to the index number, inside
square brackets.
• Similar to the way to access characters of string data type
• Example: list1=["apple", "banana", "cherry"]
print(list1[0]) “apple”
print(list1[-1]) “cherry”
print(list1[0:2]) ["apple", "banana"]
• Update: ListName[index] = new_value
list1=["apple", "banana", "cherry"]
print(list1) ["apple", "banana", "cherry"]
List1[0] = “Newapple”
print(list1) [“NewApple”, “banana”, “cherry”]
Python 41
6. Structured Data Types: Operations on Lists
• Some methods:
• append(): Add an element to the • index(): Returns the index of the
end of thelist first matched item
• extend(): Add all elements of a • count(): Returns the count of the
List to another list number of items passed as an
• insert(): Insert an item at the argument
defined index • sort(): Sort items in a List in
• remove(): Removes an item from ascending order
the list • reverse(): Reverse the order of
• pop(): Removes and returns an items in the List
element at the given index • copy(): Returns a copy of the list
• clear(): Removes all items from the • split()
list • join()
• max(); min() • …
Python 42
6. Structured Data Types: Operations on Lists
• Example:
(1) L1 = [ "a", "b", "c", "d"]
(2) L1.append("e") ["a", "b", "c", "d", "e"]
(3) L1.insert(0, "X") ["X", "a", "b", "c", "d", "e"]
(4) L1.pop() ["X", "a", "b", "c", "d"]
(5) L1.pop(0) ["a", "b", "c", "d"]
(6) L1.remove("a") ["b", "c", "d"]
(7) L1.clear() [ ]
• Method 2:
L2 = [ "a", "d", "c", "b"]
print(L2) [ "a", "d", "c", "b"]
print(sorted(L2)) [ "a", "b", "c", "d"]
print(L2) [ "a", "d", "c", "b"]
Python 44
6. Structured Data Types: Operations on Lists
• Example:
(1) cars = ["bmw", "audi", "toyota", "subaru"]
(2) print(cars) ["bmw", "audi", "toyota", "subaru"]
(3) cars.reverse()
(4) print(cars) ["subaru", "toyota", "audi", "bmw"]
• Example:
(1) cars = ["bmw", "audi", "toyota", "subaru"]
(2) len(cars) 4
Python 45
6. Structured Data Types: Operations on Lists
• Convert a string (character separator) to a list Characters : Used to list() function
• Syntax:
SourceString = "String Value"
ResultList =list(SourceString)
• Example:
(1)St = "hello"
(2)DS = list(St)
(3)print(DS) ["h", "e", "l", "l", "o"]
Python 46
6. Structured Data Types: Operations on Lists
• Split string into elements of a list : Used to split() menthod
• Syntax: StringName.split()
• Each element is identified through the space character (space key) in the
sentence.
• Example:
(1) Sentence = "subarutoyotaaudibmw"
(2) ResultList = Sentence.split()
(3) print(Sentence) "subarutoyotaaudibmw"
(4) print(ResultList) ["subaru","toyota","audi", "bmw"]
• To split a string into the elements list of a comma-defined (,):
StringName.split(",")
Python 47
6. Structured Data Types: Operations on Lists
• Concatenating strings and list: Used to join() menthod
• Append a string to each element of the list to produce a string.
• Syntax:
st = “String”
L1 = [item1, item2, …, itemLast]
st.join(L1)
Return 1 string: item1Stringitem2String … itemLast
• Example:
(1) cars = ["bmw", "audi", "toyota", "subaru"]
(2) print(cars) ["bmw", "audi", "toyota", "subaru"]
(3) space = ""
(4) print(space.join(cars)) bmwauditoyotasubaru
Python 48
6. Structured Data Types: Operations on Lists
• Merge 02 lists: Used to extend() menthod
• Syntax: List1.extend(List2)
• Append List2 into List1
• Example 1:
(1) cars = ["bmw", "audi"]
(2) cars_new = ["toyota", "subaru"]
(3) print(cars) ["bmw", "audi"]
(4) cars.extend(cars_new)
(5) print(cars) ["bmw", "audi", "toyota", "subaru"]
• Example 2:
(1) ds=[1,5,6,7,9,7,6,7,20]
(2) max(ds) 20
(3) min(ds) 1
(4) ds.count(7) 3
Python 49
6. Structured Data Types: Tuples
Python 50
6. Structured Data Types: Tuples Initialization
• One item tuple, remember the comma:
• Example:
thistuple = ("apple",)
print(type(thistuple)) <class 'tuple'>
#NOT a tuple
thistuple = ("apple")
print(type(thistuple)) <class 'str'>
Python 51
6. Structured Data Types: Operations on Tuples
• Access
• Update
• Unpacked
• Loop
• Join
Python 52
6. Structured Data Types: Operations on Tuples
• Access Tuples: can access tuple items by referring to the index number,
inside square brackets:
• Ex1: thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) banana
• Ex2: thistuple = ("apple", "banana", "cherry")
print(thistuple[-1]) cherry
Python 53
6. Structured Data Types: Operations on Tuples
• Update Tuples:
• Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
• Convert the tuple into a list, change the list, and convert the list back into a
tuple.
• Example:
x = ("apple", "banana", "cherry")
y = list(x)
y[1]="banana”
x = tuple(y)
print(x) ('apple', 'banana', 'cherry')
Python 54
6. Structured Data Types: Operations on Tuples
• Unpacked Tuples: extract the values back into variables
• Example:
# Packed Tupples
fruits = ("apple", "banana", "cherry")
# Unpacked Tupples
(green, yellow, red) = fruits
print(green) apple
print(yellow) banana
print(red) cherry
Python 55
6. Structured Data Types: Operations on Tuples
• Join Tuples:
• Ex 1: # use “+” operator
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3) ('a', 'b', 'c', 1, 2, 3)
Searches the tuple for a specified value and returns the position of
index()
where it was found
Python 57
6. Structured Data Types: Sets
• Used to store multiple items
• is a collection which is unordered, unchangeable, and unindexed.
• Items are separated by commas and enclosed in curly brackets.
• Sets Initialization
• Ex1:
thisset = {"apple", "banana", "cherry"}
print(thisset) {'banana', 'apple', 'cherry'}
• Ex2: Sets cannot have two items with the same value.
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) {'banana', 'cherry', 'apple'}
Python 58
6. Structured Data Types: Operations on Sets
• Access
• Add
• Remove
• Loop
• Join
Python 59
6. Structured Data Types: Operations on Sets
• Access:
• Cannot access items in a Sets by referring to an index.
• But we can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
• Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
cherry
print(x) apple
banana
Python 60
6. Structured Data Types: Operations on Sets
• Remove: to remove using remove() method or discard() method.
• Example 1:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset) {'cherry', 'apple'}
• Example 2:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset) {'cherry', 'apple'}
Python 61
6. Structured Data Types: Operations on Sets
• Loop: through the set items by using a for loop:
• Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset: apple
print(x) banana
• Join: using union() method or update() method. cherry
• Example:
set1 = {"a","b","c"} set1 = {"a","b","c"}
set2 = {1, 2, 3} set2 = {1, 2, 3}
set3 = set1.union(set2) set1.update(set2)
print(set3) print(set1)
{"a","b","c", 1, 2, 3} {"a","b","c", 1, 2, 3}
Python 62
6. Structured Data Types: Operations on Sets
• Sets Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified
set(s)
Python 63
6. Structured Data Types: Operations on Sets
• Sets Methods
Method Description
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Python 64
6. Structured Data Types: Dictionary
• A dictionary is a collection iteams which is ordered*, changeable and
do not allow duplicates.
• Items have <key> : <value> pairs
• Items are separated by commas and written with curly brackets
• Example: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Python 65
6. Structured Data Types: Dictionary Initialization
• Example:
# Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Python 66
6. Structured Data Types: Operations on Dictionary
• Access
• Modify
• Add
• Remove
• Loop
• Copy
Python 67
6. Structured Data Types: Operations on Dictionary
• Access: access the items of a dictionary by referring to its key name,
inside square brackets:
• Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x) “Mustang”
Python 68
6. Structured Data Types: Operations on Dictionary
• Change :
• Update dictionary: update() method will update the dictionary with the items
from the given argument
• Example: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)
Python 69
6. Structured Data Types: Operations on Dictionary
• Add Items: using a new index key and assigning a value to it
• Example: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand':'Ford','model':'Mustang','year':1964, 'color':'red'}
Python 70
6. Structured Data Types: Operations on Dictionary
• Remove Items:
• Pop() method: removes the item with the specified key name
• Example:
thisdict = {
"brand": "Ford",
"model": "Mustang", "year": 1964
}
thisdict.pop("model")
print(thisdict)
Python 71
6. Structured Data Types: Operations on Dictionary
• Remove Items:
• popitem() method: removes the last inserted item (in versions before 3.7, a
random item is removed instead)
• Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Python 73
6. Structured Data Types: Operations on Dictionary
• Loop dictionary: the return value are the keys of the dictionary, but there
are methods to return the values as well.
• Ex1: Print all key names in the dictionary, one by one:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
for x in thisdict: brand
print(x) model
year
• Ex2: Print all values in the dictionary, one by one:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
for x in thisdict: Ford
Mustang
print(thisdict[x])
1964
Python 74
6. Structured Data Types: Operations on Dictionary
• Ex3: values() method to return values of a dictionary:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
for x in thisdict.values(): Ford
print(x) Mustang
1964
• Ex4: keys() method to return the keys of a dictionary:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
for x in thisdict.keys(): brand
print(x) model
year
• Ex5: items() method to through both keys and values
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
for x,y in thisdict.items(): brand Ford
print(x,y)
model Mustang
year 1964
Python 75
6. Structured Data Types: Operations on Dictionary
• Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
Python 76
6. Structured Data Types: Operations on Dictionary
• Dictionary Methods
Method Description
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Python 77
Zip() Function
• Creating dictionaries from two • To iterate through multiple lists
lists: one for keys, one for values. at the same time
Python 78
Zip() Function
• Merging the lists list1 = [1, 2, 3]
names = ["Alice", "Bob", "Charlie"] list2 = ['a', 'b', 'c']
ages = [25, 30, 35] list3 = [True, False, True]
combined = list(zip(names, ages)) combined = list(zip(list1, list2, list3))
print(combined) print(combined)
[(1, 'a'), (2, 'b'), (3, 'c')] [(1, 'a'), (2, 'b')]
Python 79
Zip() Function
• To compare elements of Lists.
list1 = [1, 2, 3]
list2 = [1, 4, 3]
comparison = [a == b for a, b in zip(list1, list2)]
print(comparison) [True, False, True]
Python 80
7.Conditional Control Statements
• if statement
• if… else statement
• if… elif… else statement
• Nested if statement
• Short- hand if & if…else statements
Python 81
7.Conditional Control Statements: if statement
if (condition):
Statements
True
condition statements
False
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Python 82
7.Conditional Control Statements: if…else statement
if (condition):
False True
condition Statement 1
else:
Statement 2 Statement 1
Statement 2
i = 20
if (i < 15):
print("i is smaller than 15")
print("in if Block")
else:
print("i is greater than 15")
print("in else Block")
print("not in if and not in else Block")
Python 83
7.Conditional Control Statements: if… elif… else Statement
if (condition):
False Statement
Condition
elif (condition):
of if
True Statement
Statement Condition False else:
of if of elif Statement
True i = 20
Statement Statement if (i == 10):
of elif of else print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Python 84
7.Conditional Control Statements: Nested If Statement
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
i = 10
if (i == 10):
if (i < 15):
print("smaller than 15")
if (i < 12):
print("smaller than 12")
else:
print("greater than 15")
Python 85
7.Conditional Control Statements: Short-hand if & if…else statements
i = 10 False
False True
condition
Statement 1 if (condition) else statement 2 Statement 2 Statement 1
i = 10
print("A") if (i < 15) else print("B")
Python 86
8. Loop Control Statements
Python 87
8. Loop Control Statements: for Loop Statements
• is used for sequential traversals, i.e. iterate over the items of
squensence like list, string, tuple, etc.
• In Python, for loops only implements the collection-based iteration.
for variable_name in sequence :
statement_1
Last item statement_2
True reached? ....
False
Python 88
8. Loop Control Statements: while Loop Statements
while expression:
condition statement(s)
False
True
count = 0
Statement(s) while (count < 10):
count = count + 1
print(count)
Python 89
The range() function
• is used to specific number of times whereby a set of code in the for
loop is executed.
• returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
continue
print(i) 1 2 3 5 6 7 True
Condition to
continue
continue iteration
for x in range(7): False
if (x==4): Excute remaining part
continue of the loop
print(x) 0 1 2 3 5 6
Python 92
9. Functions
• Introduction to Function in python
• Types of functions
• A) Function has no parameter and no return value
• B) Function has no parameter and has a return value
• C) Function has parameter and no return value
• D) Function with many parameters
• E) Function with variable number of parameters
• F) Functions with parameter have default value
• Organize management and use of functions
Python 93
9. Functions
• Functions in python have 2 types
• Built – in function:
• Functions created by Python developers
• When needed, call the function to use
• Example:
• len()…
• float(), int(), …
• input()
• sorted(), min(), max(),..,
• Functions created by the user (called a user-defined function)
Python 94
9. Functions
• Example: The sum of the list’s elements
Python 95
9. Functions
• Replace with the following Code
def Tong_DS(ds):
sum=0
for d in ds define function
sum = sum + d
return sum
def Tong_DS(ds):
sum=0
Function for d in ds
sum = sum + d
Input: output: return sum
Parameters, possible or not - Return value
- Or done some task Function: Tong_DS(ds)
Input: Paramete is ds
Output: return value is sum
Python 97
9. Functions
• Definition syntax: • Example:
# A function to check
# whether n is even or odd
def CheckEvenOdd(n):
if (n % 2 == 0):
print("even")
else:
print("odd")
Python 98
9. Function: Types of Function
• A) Function has no parameter and no return value
• Define (create) a function:
def Name_of_Function():
" Short description of the function " # not required
Body_of_Function
• def: is a keyword.
• Name_of_Function: The function's identifier is named by the programmer.
• Body_of_Function : Contains Python statements
• Call Function: Name_of_Function() • Example:
def greet_user():
"This is a example about
Define (create) a function function"
print("Hello!")
Call Function greet_user()
Python 99
9. Function: Types of Function
• B) Function has no parameter and has return value
• Define (create) a function:
def Name_of_Function():
" Short description of the function "
Body_of_Function
return value
def greet_user():
"This is a example about function“
x = 5 + 6
return x
Python 100
9. Function: Types of Function
• C) Function has parameter and no return value
• Define (create) a function:
def Name_of_Function(Parameter):
" Short description of the function "
Body_of_Function
Python 97
101
9. Function: Types of Function
• D) Function with many parameters
• Define (create) a function:
def Name_of_Function(Parameter1, Parameter1…):
" Short description of the function " # not required
Body_of_Function
Python 102
9. Function: Types of Function
• E) Functions with parameter have default value
• Define (create) a function:
def Name_of_Function(Parameter1, Parameter2= default value,…):
" Short description of the function "
Body_of_Function
• Call function: Name_of_Function(Argument1)
• Value of argument1 will be passed into parameter1
• Value of Parameter2 is default value
• Example: Define (create) a function
def greet_user(name, age="22"):
print(“My name is" + name.title())
print(“My age is" + age)
• Call fuction:
name="dũng" My name is Dũng
greet_user(name) My age is 22
Python 103
9. Function: Types of Function
• F) Function with special parameter
• Example:
• Define a function: def sum_03_so(a, b, c):
print(“Sum 03 number is: ", a+b+c)
• Call Function: x1, x2, x3 = 10, 20, 30
sum_03_so(x1, x2, x3) 60
Python 105
9. Function: Types of Function
• Example of Function with special parameter :
def myFun(*a):
Welcome
for i in args:
to
print(i)
VKU
myFun('Welcome', 'to', 'VKU')
def myFun(**a):
for key, value in a.items(): first Welcome
print(key, value)) second to
myFun(first='Welcome', second='to', last='VKU') last VKU
Python 106
9. Function: Organize storage and use functions
Python 107
9. Function: Organize storage and use functions
• Step 1: Create sum.py
import sum
list_odd = [ 11, 13, 15, 17, 19, 21] Call Function
sum1 = sum.Sum_list(ds_le)
print(“Sum of items in List : ", sum1)
Python 108
9. Function: Organize storage and use functions
• Method 2:
• Step 1: Define (Create) functions and save in a separate file (Module File)
• Step 2: Import Module File into main program by used to import command
• Type 1: from Module import FunctionName
• Type 2: from Module import FunctionName_1, FunctionName_2, …
• Type 3: from Module import *
• Step 3: Used to function (call function) according to the syntax: FunctionName
Python 109
9. Function: Organize storage and use functions
• Step 1: Create sum.py file
Python 110
9. Function: Organize storage and use functions
• Method 3: Used to an alias
• Step 1: Create functions and save in a separate file (Module File)
• Step 2: Import Module File into main program by used to import
command, and Used to an alias
from Module import FunctionName as alias
• Step 3: Sử dụng hàm gọi hàm theo cú pháp: alias
Python 111
9. Function: Organize storage and use functions
• Step 1: Create a sum.py file
Python 112
Practice and exercises
Part 2
Python 113
10. File Handling
• Opening file
• Reading file
• Writing to file
• Appending file
• With statement
Python 114
10. File Handling: Opening file
• Using the open() function : File_object=open(filename, mode)
• filename: the name of file
• mode: represents the purpose of the opening file with one of the
following values:
• r: open an existing file for a read operation.
• Example: • w: open an existing file for a write operation.
# a file named "sample.txt", will • a: open an existing file for append
be opened with the reading mode. operation.
file = open('sample.txt', 'r') • r+: to read and write data into the file. The
# This will print every line one by previous data in the file will be overridden.
one in the file • w+: to write and read data. It will override
for each in file: existing data.
print(each) • a+: to append and read data from the file. It
won’t override existing data.
Python 115
10. File Handling: Reading file
• Using the read() method: File_object.read(size)
• size <=0: returning a string that contains all characters in the file
# read() mode
file = open("sample.txt", "r")
print(file.read())
Python 116
10. File Handling: Close file
• Using close() method to close the file and to free the memory space
acquired by that file
• Used at the time when the file is no longer needed or if it is to be
opened in a different file mode.
File_object.close()
Python 117
10. File Handling: Writing to file
• Using the write() method to insert a string in a single line in the text file
and the writelines() mwthod to insert multiple strings in the text file at
a once time. Note: the file is opened in write mode
File_object.write/writelines(text)
• Example:
file = open('sample.txt', 'w')
L = ["VKU \n","Python Programming\n","Computer Science \n"]
S = "Welcome\n"
# Writing a string to file
file.write(S)
# Writing multiple strings at a time
file.writelines(L)
file.close()
Python 118
10. File Handling: Appending File
• Using the write/writelines() method to insert the data at the end of the
file, after the existing data. Note: the file is opened in append mode
• Example:
file = open('sample.txt', 'w') # Write mode
S = "Welcome\n"
# Writing a string to file
file.write(S)
file.close()
# Append-adds at last
file = open('sample.txt', 'a') # Append mode
L = ["VKU \n","Python Programming\n","Computer Science\n"]
file.writelines(L)
file.close()
Python 119
With statement
• used in exception handling to make the code cleaner and to ensure
proper acquisition and release of resources.
• using with statement replaces calling the close() method
Python 120
11. Exception Handling
• try … Except Statement
• try … except… else … finally Statement
Python 121
11. Exception Handling: Try ... Except Statement
• Try and except statements are used to catch and handle exceptions in
Python.
try :
statements
except :
executed when error in try block
• Example:
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")
Python 122
11. Exception Handling: Try … except… Else … Finally Statement
• The else block gets processed if the try block is found to be exception
free (no exception).
• The finally block always executes after normal termination of try block
or after try block terminates due to some exception
try:
statements in try block
except:
executed when error in try block
else:
executed if no exception
finally:
executed irrespective of exception occured or not
Python 123
11. Exception Handling: Try … except… Else … Finally Statement
• Example:
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print("Out of try, except, else and finally blocks.")
Python 124
Practice and exercises
Part 3
Python 125