2. Fundamentals of Python Programming
2. Fundamentals of Python Programming
2. Fundamentals of Python Programming
Introduction
Installation of IDE for Python
Python Programming Basics
Built-In Data Structures in Python
Expressions and Functions
I/O with Files in Python
Exercises/Practices
10/26/2024 Dr. Mai Cao Lan - Faculty of Geology & Petroleum Engineering, HCMUT 25
Introduction
Python is a popular programming language. It was created by
Guido van Rossum, and released in 1991.
Large standard
libraries
Interpreted
language
Cross-platform
language
Object-oriented
language GUI support
10/26/2024 Dr. Mai Cao Lan - Faculty of Geology & Petroleum Engineering, HCMUT 26
History of Python (Timeline)
Python 0.9.0 was Python 2.0 was released, Python 2.7 reached the end
released with the improved garbage of its life (no security patches
philosophy of simple collection for better memory or updates were introduced).
and readable code management and list Version 3.0 and later are
comprehension for creating supported.
new lists more concisely than
before.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 27
Introduction
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 28
Python IDEs and Code Editors
Criteria IDEs Code editors
- Write and edit codes as a code editor.
- Integrates additional tools like
+ a debugger - Write and edit codes with additional
+ compiler, or interpreter features:
+ version control + syntax highlighting
Features
+ build automation + auto-completion
+ code testing tools + auto code formatting
+ code analyzing + ...
+ GUIs creating
+ ...
- Suitable for larger projects or when you - Ideal for quick code edits, simple
need to manage multiple aspects of scripts, or when you don’t need the
Usage
development, from writing code to full suite of development tools
testing and deployment. provided by an IDE.
- IDLE (pre-installed with Python)
- Notepad++
- PyCharm
- Sublime Text
- Spyder
- Visual Studio Code (can be extended
Tools - Eclipse
with plugins to become more like an
- IntelliJ IDEA
IDE).
- Visual Studio
- ...
- ...
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 29
Procedure of Python Installation
Download and run Python installer:
https://www.python.org/downloads/windows/
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 30
Procedure of Python Installation
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 31
Verifying Python Installation in Windows
Check pip version: type pip --version and press Enter. This
verifies that pip, Python's package installer, is also installed.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 32
Install JupyterLab using pip
Press Win + R, type cmd, and press Enter.
jupyter lab
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 33
Installing VS Code for Python Programming
Download and install Miniconda
https://docs.anaconda.com/miniconda/miniconda-install/
conda –version
https://code.visualstudio.com/download
From now on, you can run VS Code from a terminal window
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 35
Python Indentation
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 36
Popular operators in Python
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 37
Python Arithmetic Operators
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 38
Python Arithmetic Operators
Active learning with application in mind
Quiz 1 Quiz 2
x = 5 x = 5
y = 2 y = 2
print(x % y) print(x // y)
>>> >>>
??? ???
3. Applications:
== Equal x == y
!= Not equal x != y
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 41
Python Comparison Operators
Quiz 1 Quiz 2
x = 5 x = 5
y = 3 y = 3
print(x == y) print(x != y)
>>> >>>
??? ???
Quiz 5 Quiz 6
x = 5 x = 5
y = 3 y = 3
print(x >= y) print(x <= y)
>>> >>>
??? ???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 43
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description Example
Sets each bit to 1 if both bits are
& AND x & y
1
Sets each bit to 1 if one of two
| OR x | y
bits is 1
Sets each bit to 1 if only one of
^ XOR x ^ y
two bits is 1
~ NOT Inverts all the bits ~x
Shift left by pushing zeros in from
Zero fill
<< the right and let the leftmost bits x << 2
left shift
fall off
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 44
Python Bitwise Operators
Exercise
A= 1 0 0 1
B= 0 0 1 1
C= ? ? ? ?
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 45
Python Variables
A variable acts as a container with a value, which could be a
number, string, or list, ...
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 46
Creating Variables
Python has no command for declaring a variable.
Quiz 1 Quiz 2
x = 5
value = 5
y = "Data scientists"
variable_name = value
print(x)
print(variable_name)
print(y)
>>> >>>
??? ???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 47
Casting of Variable
The casting of variables involves converting a variable from one
data type to another.
Quiz 1 Quiz 2
x = str(3)
y = int(3) int_var = 5
z = float(3) cast_to_bool = bool(int_var)
t = complex(3) print(cast_to_bool)
print(x, y, z, t)
>>> >>>
??? ???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 48
Get the type of variable
The data type of a variable is gotten with the type() function.
Quiz 1
x = 5
y = "John"
print(type(x))
print(type(y))
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 49
Single or Double Quotes?
Quiz 1
x = "John"
y = 'John’
print(x, y)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 50
Case-Sensitive
Variable names are case-sensitive.
a = 4
A = “Peter"
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 51
Rules for creating a variable
Ensure that the name only includes letters, numbers, and
underscores. No other special characters are permitted like
@,#,&. ❌
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 52
Assigning multiple variables
In Python, multiple variables can be assigned simultaneously.
Quiz 1
a, b = 1000000, 5000
print(a, b)
>>>
???
Quiz 2
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
>>>
????
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 53
Assigning the same value to multiple
variables
Syntax
Quiz 1 Quiz 2
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 54
Packing/Unpacking a collection
Quiz 1: Packing
my_tuple = 1, 2, 3
print(my_tuple)
>>>
???
Quiz 2: Unpacking
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 55
Output Variables
The Python print() function is often used to output variables.
Quiz 1
x = "Python is awesome"
print(x)
>>>
???
Quiz 2
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 56
Output Variables
Syntax
Quiz 8
Common Escape Sequences:
\n Newline print(???)
\t Tab
>>>
\\ Backslash Hello World
\’ Single quote Python is awesome!
\’’ Double quote
\uXXXX Unicode character
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 57
Primitive data type
There are three popular data types in Python:
Numeric type
String type
Boolean type
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 58
Numetric types in Python
There are three numeric types in Python:
int
float
complex
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 59
Convert Numeric Types in Python
Syntax
new_variable = new_type(value)
Quiz 1
x = 1
y = 2.8
z = 1j
#convert to float:
a = float(x)
#convert to int:
b = int(y)
#convert to complex:
c = complex(x)
print(a)
print(b)
print(c)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 60
String type in Python
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 61
Slicing strings in Python
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 62
Loops in Python
The main aspects associated with loops in Python:
o Loop control: use break, continue, and pass to control the flow.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 63
for loop in Python
Syntax
for item in sequence:
# Code to execute
Example 1
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 64
Range with for Loops
Syntax
for i in range(start, stop, step):
# code block to execute
Example 1
# Print numbers 0 to 4
for i in range(5):
print(i)
>>>
0
1
2
3
4
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 65
for loop with else
Syntax
for item in sequence:
<code to execute>
else:
<code to execute>
Example 1
>>>
10
11
12
Loop complete
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 66
while loop in Python
Syntax
while condition:
# code block to execute
Syntax
while <condition>:
<code to execute>
else:
<code to execute>
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 67
for or while?
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 68
Loop Control Statements
break: Exits the loop prematurely.
continue: Skips the rest of the current iteration and moves to the next.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 69
break statement in loops
Syntax
for loop
#some for block code
if condition:
break
#some more code
#outside the loop
Syntax
while expression:
#some code
if condition:
break
#some more code
#outside the loop
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 70
continue statement in loops
Syntax
for loop
#some for block code
if condition:
continue
#some more code
#outside the loop
Syntax
while expression:
#some code
if condition:
continue
#some more code
#outside the loop
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 71
continue statement in loops
Example 2
>>>
Found the letter ‘a’ in position: 10
Found the letter ‘a’ in position: 17
Found the letter ‘a’ in position: 25
Found the letter ‘a’ in position: 29
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 72
pass statement in loops
Syntax
Syntax
while expression:
# some code
pass
# more code
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 73
Nested loops
Nested loops are simply loops within loops.
Syntax
for outer_loop_variable in outer_sequence:
for inner_loop_variable in inner_sequence:
# Code to be executed for each iteration of the
inner loop
Example
for i in range(1, 11):
for j in range(1, 11):
print(i*j, end=" ")
print()
>>>
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 74
Built-In Data Structures in Python
Python provides several built-in data structures to efficiently
store and manage collections of data.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 75
Built-In Data Structures in Python
There are four popular built-in data structures in Python:
List
Tuple
Set
Dictionary
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 76
Summary of Data Structure in Python
Allows
Data structure Ordered Changeable Key Characteristics
duplicates
Best for ordered, changeable
List Yes Yes Yes
collections
Tuple Yes No Yes Ideal for fixed, ordered data
Best for unique, unordered
Set No Yes No
items
Keys: No, Values:
Dictionary Yes* Yes Best for key-value pair data
Yes
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 77
Python Lists
A list in Python is a data collection of any type (strings , integers,
floating point numbers, etc ...).
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 78
Creating a List in Python
Syntax
item = my_list[index]
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 79
List Slicing in Python
Syntax
list_name[start:stop:step]
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 80
Methods for List Manipulation
List methods Functionality
append() Adds an element to the end of a list.
Inserts an element at a specific position in a
insert()
list.
extend() Adds multiple elements to the end of a list.
Removes an element from a specific position in
pop()
a list and returns it.
Removes the first occurrence of a specific
remove()
element from a list.
Returns the index of the first occurrence of a
index()
specific element in a list.
sort()
10/26/2024 Sorts the elements in a list in ascending order.
81
Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam
Build-In Functions for List
Functions Functionality
len() Returns the number of elements in a list.
min() Returns the smallest element in a list.
max() Returns the largest element in a list.
sum() Returns the sum of all elements in a list.
sorted() Returns a sorted list of elements.
reversed() Returns a reversed list of elements.
Returns a list of tuples containing the index
enumerate()
and element of each element in a list.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 82
Python Tuples
A tuple is a collection of objects separated by comma (,) inside
the parentheses ().
Quiz 1:
When would we use a tuple over a list?
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 83
Creating a tuple in Python
Syntax
Quiz 1
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 84
Allow Duplicates in Python Tuples
Since tuples are indexed, they can have items with the same
value.
Example 1
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 85
Accessing tuple elements
Syntax
tuple_name[index]
Quiz 1
my_tuple = (1, 2, 3, 4, 5)
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 86
Tuple Unpacking
Syntax
Quiz 1
print(green)
print(yellow)
print(red)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 87
Tuple Methods
Two built-in methods can be used on tuples in Python:
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 88
Python Sets
A set is a built-in Python data structure that represents an
unordered collection of unique elements.
Quiz 1:
What is the main advantage of using sets over lists?
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 89
Creating a set in Python
Syntax
Quiz 1
my_set = {1, 2, 3, 4}
print(my_set)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 90
Duplicates NOT Allowed for Python Set
Quiz 1
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 91
Notes of Python Sets
True and 1 are identical
print(thisset)
>>>
???
Quiz 2
thisset = {"apple", "banana", "cherry", False, True, 0}
print(thisset)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 92
Accessing Set Items
Syntax
Quiz 1
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
>>>
???
Quiz 2
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 93
Adding an item to the set
To add one item to a set use the add() method.
Quiz 1
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 94
Removing an item from the set
To remove an item in a set, use the remove(), or the discard()
method.
Quiz 1
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 95
Set’s Methods
Quiz 1
set1 = {1, 2, 3}
set2 = {3, 4, 5}
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 96
Set methods
Method Shortcut 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)
isdisjoint() Returns whether two sets have a intersection or not
issubset() <= Returns whether another set contains this set or not
< Returns whether all items in this set is present in
other, specified set(s)
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 97
Set’s Methods
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 98
Python Dictionaries
A dictionary is a collection of key-value pairs.
Quiz 1:
What is the purpose of a key in a dictionary?
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 99
Creating Dictionaries
Syntax
Quiz 1
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 100
Accessing Values
Syntax
value = my_dict[key]
or value = my_dict.get(key)
Quiz 1
# Using curly braces
Quiz 2
my_dict = {
"name": "Bob", my_dict = dict(name="Charlie", age=35)
"age": 25 # Using get() method
} age = my_dict.get("age")
name = my_dict["name"] print(age)
print(name) >>>
>>> ???
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 101
Adding and modifying Entries
Syntax (modifying)
my_dict[existing_key] = new_value
Syntax (adding)
my_dict[new_key] = new_value
Quiz 1
my_dict = {
"name": "Bob",
"age": 25
}
my_dict["email"] = "bob@example.com" # Adding a new key-value
pair
my_dict["age"] = 31 # Modifying an existing value
print(my_dict)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 102
Updating Entries
Syntax
my_dict.update({key1: value1, key2: value2})
Quiz 1
my_dict = {
"name": "Bob",
"age": 30
}
# Adding and modifying entries using update()
my_dict.update({"age": 32, "job": "Engineer"})
print(my_dict)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 103
Removing Entries
Entries can be removed using the del statement or the pop()
method.
Quiz 1
my_dict = {
"name": "Bob",
"age": 25,
"email": "bob@example.com",
"city": "New York",
"nationality": "U.S"
}
del my_dict["city"] # Removing an entry
email = my_dict.pop("email") # Removing and getting the value
print(my_dict)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 104
Iterating Over Dictionaries
Dictionaries can be iterated over keys, values, or key-value pairs.
Quiz 1
my_dict = {
"name": "Bob",
"age": 25,
"email": "bob@example.com",
"city": "New York",
"nationality": "U.S"
}
for key in my_dict: # Iterating over keys
print("Ans_1: ", key)
for value in my_dict.values():# Iterating over values
print("Ans_2: ", value)
for key, value in my_dict.items(): # Iterating over key-value
pairs
print("Ans_2: ",key, value)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 105
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 106
Comprehension in Python
Comprehension is a concise way to create a new list, set, or
dictionary based on an existing iterable object.
o List comprehensions
o Set comprehensions
o Dictionary comprehensions
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 107
List Comprehension
Syntax
new_list = [expression for variable in iterable if condition]
Quiz 1
numbers = [1, 2, 3, 4, 5]
squared_numbers = [y**2 for y in numbers]
print(squared_numbers)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 108
Set Comprehension
Syntax
new_set = {expression for variable in iterable if condition}
Quiz 1
numbers = [1, 2, 3, 4, 5]
squared_numbers = {x**2 for x in numbers}
print(squared_numbers)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 109
Dictionary Comprehension
Syntax
new_dict = {key_expression: value_expression for variable in
iterable if condition}
Quiz 1
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 110
Python Functions
A function is a reusable block of code that performs a specific task
and can return a result.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 111
Python Functions
Example 1
def greet(name):
return f"Hello, {name}!“
>>>
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 112
Python Functions
Quiz 1
def my_function(a, b=2):
return a * b
result = my_function(3)
print(result)
>>>
???
Quiz 2
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
results = factorial(5)
print(results)
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 113
Lambda functions
Lambda functions, also known as anonymous functions, are small,
one-line functions without a name.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 114
Lambda functions
Quiz 1
>>>
???
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 115
Input/output with Files in Python
File I/O in Python involves reading from and writing to files.
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 116
Input/output with Files in Python
File handling type Description Syntax
Open a file for reading,
Opening Files file = open('filename', 'mode')
writing, or appending.
Close an opened file to free up
Closing Files file.close()
system resources.
Read the entire content of a
Reading Entire File content = file.read()
file as a single string.
Read one line from the file at
Reading Line by Line line = file.readline()
a time.
Read all lines into a list,
Reading All Lines lines = file.readlines()
where each item is a line.
Write a string to the file,
Writing to a File file.write('text')
overwriting if it exists.
Add text to the end of the file file = open('filename', 'a’)\n
Appending to a File
without overwriting. file.write('text')
Automatically handles with open('filename', 'mode') as file:\n
Using with Statement
opening and closing of files. # File operations
Handle binary files, not text
Binary Mode file = open('filename', 'rb') (read binary)
files.
Manage errors during file try:\n with open('filename', 'r') as file:\n
Handling Exceptions
operations. # Operations\nexcept IOError as e:\n print€
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 117
Input/output with Files in Python
'r': Read mode. The file is opened for reading (default).
'w': Write mode. The file is opened for writing. If the file already exists, its
contents will be truncated. If the file does not exist, a new file will be created.
'a': Append mode. The file is opened for writing, and data is appended to the end
of the file.
'x': Exclusive creation mode. The file is opened for writing, but only if it does not
already exist.
'b': Binary mode. The file is opened in binary mode, which is used for non-text
files like images or audio files.
't': Text mode. The file is opened in text mode, which is used for text files
(default).
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 118
Input/output with Files in Python
Example (opening file)
file = open('example.txt', 'r') # 'r' for read mode
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 119
Input/output with Files in Python
Example (writing to a file)
file = open('example.txt', 'w')
file.write('Hello, World!')
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 120