2. Fundamentals of Python Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 97

10/26/2024 Dr.

Mai Cao Lan - Faculty of Geology & Petroleum Engineering, HCMUT 24


Chapter Outline

 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.

Easy to code Large


community
High-level Open source
language

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 Python 1.0 was released Python 3.0 was released,


conceived including features for removed obsolete
functional programming, features to fix inconsistencies
streamlining the in syntax. The version was not
processing of large backward-compatible with
amounts of data. earlier ones, forcing the update
of existing programs

1980 1991 1994 2000 2008 2020

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:

o Open a web browser: go to the official Python download for


Windows website:

https://www.python.org/downloads/windows/

o Select the latest version (Python 3.12.5). Click on Windows


installer (64-bit) for 64-bit system.

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

 Press Win + R, type cmd, and press Enter to open the


Command Prompt window.

 Type python --version and press Enter to check Python


version.

 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.

Install JupyterLab with pip:

pip install jupyterlab

launch JupyterLab with:

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/

Open the terminal window and check your conda installation

 conda –version

Create a new virtual environment (e.g. da-env)

 conda create --name da-env

Deactivate the (default) base environment and activate the


recently created environment
 conda deactivate
 conda activate da-env
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 34
Installing VS Code for Python (cont’d)
Download and install Visual Studio Code

 https://code.visualstudio.com/download

Run VS Code and install the following extensions inside VS Code


 Python
 Pylance
 Jupyter notebook/lab
 Ipykernel (for Jupyter notebook to work inside VS Code)
From inside VS Code, open the command palette and type “Shell
Command” then select “Shell Command: Install ‘code’ command
in PATH”

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

Operator Name Example

+ 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)
>>> >>>
??? ???

1. When do we use the operator %?

2. For which cases do we need to use the operator //?

3. Applications:

a. Check if a number is odd or even

b. Get the quotient and the remainder of x/y


10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 39
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3
print(x)
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 40
Python Comparison Operators
Comparison operators are used to compare two values

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x > y

< Less than x < y

>= Greater than or equal to x >= y

<= Less than or equal to 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)
>>> >>>
??? ???

What are the result types from these operators?

Refer back to the odd-even number identification for a


usage demonstration
10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 42
Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example


Returns True if both
and x < 5 and x < 10
statements are true
Returns True if one of the
or x < 5 or x < 4
statements is true
Reverse the result, returns
not not(x < 5 and x < 10)
False if the result is true

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

Signed Shift right by pushing copies of the


>> right leftmost bit in from the left, and x >> 2
shift let the rightmost bits fall off

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 44
Python Bitwise Operators

Exercise

We have two 6-digit LEDs named A and B. Add another LED


named C so that each digit of the LED C is ON if and only if just
one of the corresponding digits of A and B is ON.

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.

A variable is created the moment you first assign a value to it.

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?

String variables can be assigned either by using 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.

Quiz 1: How many variables does the block of code contain?

a = 4
A = “Peter"

1. One variable (A)


2. One variable (a)
3. Two variables
4. Variable assignment error

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
@,#,&. ❌

The variable name should either begin with an Uppercase(A to


Z) or Lowercase(a to z) character or an underscore(_).

The name must not begin with a number. ❌

The name is case-sensitive, meaning "age" and "Age" are two


different variables.

Avoid using Python-reserved words as variable names.

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

var1, var2, ..., varN = value

Quiz 1 Quiz 2

number1 = number2 = number3 = 899 x = y = z = "Orange"


print(number1,number2,number3) print(x)
print(y)
>>> print(z)
???

>>>
???

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

print("Your text here with special characters: \\n, \\t, etc.")

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 for loop: iterate over a sequence.

o while loop: continue executing as long as a condition is true.

o Loop control: use break, continue, and pass to control the flow.

o Nested Loops: use loops inside loops for multidimensional data.

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

for i in [1, 2, 3, 4, 5]:


print(i)
>>>
1
2
3
4
5

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

for i in range(10, 13):


print(i)
else:
print("Loop complete")

>>>
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?

for loop: used when the number of iteration is known.

while loop: used when the number of iterations is unknown

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.

pass: Do nothing, acts as a placeholder.

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

string = "Python is a programming language"

for index in range(len(string)):


if string[index] != 'a':
continue
else
print("Found the letter ‘a’ in position:", index)

>>>
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

for variable in iterable:


# some code
pass
# more code

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.

These structures vary in characteristics such as changeability,


order, and uniqueness, and are essential for writing clean,
efficient Python code.

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

*As of Python version 3.7, dictionaries are ordered. In Python 3.6


and earlier, dictionaries are unordered.

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

variable_name = [list of elements separated by comma]

Accessing List Items


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?

A. When we need a collection of changeable items.

B. When data should remain constant (unchangeable).

C. When we want to append or remove items frequently.

D. When we need to sort items.

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 83
Creating a tuple in Python
Syntax

variable_name=(elements separated by commas)

Quiz 1

this_tuple = ("apple", "banana", "cherry")


print(this_tuple)

>>>
???

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

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

>>>
???

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)

# Accessing the first element of the tuple


print(my_tuple[0])
# Accessing the third element of the tuple
print(my_tuple[2])
>>>
???

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 86
Tuple Unpacking
Syntax

var1, var2, ..., varN = tuple

Quiz 1

fruits = ("apple", "banana", "cherry")

green, yellow, red = fruits

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:

o count(): Returns the number of times a specified value


occurs in a tuple.

o index(): Searches the tuple for a specified value and returns


the position of where it was found

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?

A. Sets are ordered

B. Sets can contain duplicate elements.

C. Sets are more efficient for checking membership.

D. Sets are changeable.

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 89
Creating a set in Python
Syntax

variable_name={elements separated by comma}

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

False and 0 are identical


Quiz 1
thisset = {"apple", "banana", "cherry", True, 1, 2}

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

for item in my_set:


print(item)

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

fruits = {"apple", "banana", "cherry"}


fruits.add("orange")
print(fruits)

>>>
???

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

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")
print(fruits)

>>>
???

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}

union = set1 | set2 #Union of set1 and set2 (elements in either


set)
intersection = set1 & set2 #Intersection of set1 and set2
(elements in both sets)
difference = set1 - set2 #Difference of set1 and set2 (elements
in set1 but not in set2)
print(union)
print(intersection)
print(difference)
>>>
???

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

issuperset() >= Returns whether this set contains


another set or not
> Returns whether all items in other,
specified set(s) is present in this set
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

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.

Keys are not allowed to duplicate, but values are allowed.

Quiz 1:
What is the purpose of a key in a dictionary?

A. To store the value of an element.

B. To provide a unique identifier for each value.

C. To maintain the order of elements.

D. To perform calculations on the values.

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 99
Creating Dictionaries
Syntax

my_dict = {key1: value1, key2: value2, ...}

Quiz 1

# Using curly braces Quiz 2


my_dict = { # Using dict() constructor
"name": "Bob", my_dict = dict(name="Charlie", age=35)
"age": 25 print(my_dict)
}
print(my_dict)
>>>
>>> ???
???

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

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

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

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.

There are three types of comprehension in Python:

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

numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}


squared_numbers = {key: value**2 for key, value in
numbers.items()}
print(squared_numbers)
>>>
???

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.

Functions are defined using the def keyword followed by the


function name and parentheses.

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}!“

>>>

o def: This keyword is used to define a new function in Python.


o greet: This is the name of the function.
o (name): These are the parameters of the function.
o f"Hello, {name}!": This is an f-string in Python, the value of the name
parameter will be inserted into the string.
o return: This keyword is used to send a value back from a function.

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

# A lambda function that adds 10 to a given number


add_10 = lambda x: x + 10

# Calling the lambda function


result = add_10(5)
print(result)

>>>
???

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.

Python provides built-in functions to handle file operations like


opening, reading, writing, and closing files, etc.

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

Example (closing file)


file.close()

Example (reading entire file)


content = file.read()

Example (reading all lines)


lines = file.readlines()

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!')

Example (appending to a file)


file = open('example.txt', 'a')
file.write('Appended text.')

Example (Using with Statement)

with open('example.txt', 'r') as file:


content = file.read()

10/26/2024 Dr. Mai Cao Lân, Faculty of Geology & Petroleum Engineering, HCMUT, Vietnam 120

You might also like