Chapter 2 Python Basics
Chapter 2 Python Basics
Python Basics
Si Thin Nguyen
PhD in Computer Science at Soongsil University, Korea
Email: nsthin@vku.udn.vn
Address: Faculty of Computer Science, VKU
Chapter Content
➢ Syntax
➢ Variables - Operators
➢ Fundamental Data types
➢ Control flow statements
➢ Loop control statements
➢ Function
➢ File Handling
➢ Exception Handling
Syntax
➔ Keywords in Python
Syntax
➔ Indentation which refers to the spaces at the beginning of a code
line is obligated to use to indicate a block of code in control flows,
classes or functions
Indentation if 6 > 3 :
print("Six is greater than three!")
#This is a comment
print("Hello, World!")
➔ Multi-line commands can also use [], {}, () and need not use \
days = ['Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday']
➔ Variables can also specific to the particular data type with casting
x = str(3) # x will be '3'
y = int(3) # y will be 3
Variables
➔ Many values can be assigned to multiple variables
Clear() Removes all items from the list copy() Returns a copy of the list
Data Structures
➢ Lists
➢ Tuples
○ Tuples Initialization
○ Operations on Tuples
○ Tuples methods
➢ Dictionary
➢ Sets
Tuples
➔ Tuples are used to store multiple items in a single variable.
➔ A tuple is a collection which is ordered and unchangeable
➔ are written with round brackets.
➔ Example:
Searches the tuple for a specified value and returns the position of where it
Index()
was found
thisset.remove("banana")
print(thisset)
thisset.discard("banana")
print(thisset)
Operations on Sets
➔ Loop: through the set items by using a for loop:
o Ex:
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
intersection_update() Removes the items in this set that are not present in other, specified set(s)
Sets Methods
Method Description
isdisjoint() Returns whether two sets have a intersection or not
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Data Structures
➢ Lists
➢ Tuples
➢ Sets
➢ Dictionary
○ Dictionary Initialization
○ Operations on Dictionary
○ Dictionary methods
Dictionaries
➔ Are used to store data values in key : value pairs.
➔ A dictionary is a collection which is ordered*, changeable
and do not allow duplicates.
➔ written with curly brackets, and have keys and values:
Dictionaries Initialization
➔ Ex1: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionaries Initialization
🡪 Ex2:
# Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Operations on Dictionaries
➔ Access Items
➔ Change Items
➔ Add Items
➔ Remove Items
➔ Loop Items
➔ Copy Dictionaries
Operations on Dictionaries
➔ Access Items: access the items of a dictionary by
referring to its key name, inside square brackets:
➔ Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Operations on Dictionaries
➔ Change Items:
o Update dictionary: update() method will update the
dictionary with the items from the given argument
o Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Operations on Dictionaries
➔ Add Items: using a new index key and assigning a
value to it
➔ Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Operations on Dictionaries
➔ Remove Items:
o Pop() method: removes the item with the specified
key name:
o Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Operations on Dictionaries
➔ Remove Items:
o popitem() : removes the last inserted item (in versions
before 3.7, a random item is removed instead):
o Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Operations on Dictionaries
➔ Remove Items:
o del : delete the dictionary completely
o Clear(): empties the dictionary:
o Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error
because "thisdict" no longer exists.
thisdict.clear()
print(thisdict)
Operations on Dictionaries
➔ Loop dictionaries: the return value are the keys of the
dictionary, but there are methods to return the values as
well.
o Ex1: Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
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
Dictionaries 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
Conditional Control Statements
○ If statement
○ If… else statement
○ If… elif… else statement
○ Nested If statement
○ Short- hand if & if…else statements
If statement
if condition:
# Statements to execute if condition is true
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
If…else statement
if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false
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")
If… elif… else Statement
if (condition):
statement
elif (condition):
... statement
else:
statement
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
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")
Short- hand if & if…else statements
➔ If there is only one statement to execute, the If & If … else
statements can be put on the same line
if condition: Statement
i = 10
if (i > 15): print("10 is less than 15")
i = 10
print(True)if (i < 15) else print(False)
Loop Control Statements
○ for loop statements
○ while loop statements
○ The range() function
○ Loops with break statement
○ Loops with continue statement
○ Loops with else statement
○ Loops with pass statement
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
statement_2
....
l = ["red", "blue", "green"]
for i in l:
print(i)
while Loop Statements
➔ is used to execute a block of statements repeatedly until a
given condition is satisfied.
➔ can fall under the category of indefinite iteration when the
number of times the loop is executed isn’t specified
explicitly in advance. while expression:
statement(s)
count = 0
while (count < 10):
count = count + 1
print(count)
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.
range(start_number, last_number, increment_value)
File_object.close()
Writing to file
➔ Using the function write()to insert a string in a single line in the text
file and the function writelines()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)
Ex:
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")
Try with Else and Finally Clauses