The python fundamental introduction part 1

DeoDuaNaoHet 83 views 95 slides Sep 19, 2024
Slide 1
Slide 1 of 95
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95

About This Presentation

Python introduction


Slide Content

By: Võ Văn Hải
Email: [email protected]
1
Python for Data Science
Part 1: Fundamentals

Lecturer information
▸Full name: Võ Văn Hải
▸Email: [email protected]
▸Scopus:
https://www.scopus.com/authid/detail.uri?authorId=57211989550
▸Google scholar:
https://scholar.google.com/citations?hl=en&user=MvT6c8YAAAAJ
2

Ask
The art and science of asking questions is the source of all knowledge.
- Thomas Berger
▸Do not hesitate to ask!
▸If something is not clear, stop me and ask.
▸During exercises (you can also ask others).
3
Source: Chicken Soup for the Soul

Failure
▸Coding is all about trial and error.
▸Don't be afraid of it.
▸Error messages aren't scary, they are useful.
4

Introduction to
5

6

History
▸Started by Guido Van Rossum as a hobby
▸Now widely spread
▸Open Source! Free!
▸Versatile
7
The designer of Python,
Guido van Rossum, at OSCON
2006 (src: wikipedia)
Source: unstop.com

Programming Languages of 2024
8
Source: https://www.simform.com/blog/top-programming-languages/

Start with python
▸Install Python
-https://www.python.org/
▸Python tutorial
-https://docs.python.org/3/tutorial/
-…
-Ask google
▸IDEs
9

Your First Python Program
11

Comment
▸Comments can be used to:
-explain Python code.
-make the code more readable.
-prevent execution when testing code.
▸Comments starts with a #, and Python will ignore them
▸Single line comments
▸Multiline Comments
12
# This is a comment
print("Hello, World!") # This is a comment
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Variables
▸Let us calculate the distance between Edinburgh and London in km
▸Great calculator but how can we make it store values?
→ Do this by defining variables
▸The value can later be called by the variable name
▸Variable names are case sensitive and unique
The variable mileToKm can be used in the next block without having to define it again
13
Python as a calculator

Variables
▸Variables are containers for storing data values.
▸Creating Variables
-Python has no command for declaring a variable.
-A variable is created the moment you first assign a value to it.
▸Variables do not need to be declared with any particular type, and can
even change type after they have been set.
15
x = 5
y = "John"
print(x)
print(y)
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
# If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
# You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))

Variables
▸A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables:
-A variable name must start with a letter or the underscore character
-A variable name cannot start with a number
-A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
-Variable names are case-sensitive (age, Age and AGE are three different variables)
-A variable name cannot be any of the Python keywords.
▸Variable names with more than one word can be difficult to read. -->
several techniques you can use to make them more readable:
16
Variable Names
Camel Case Pascal Case Snake Case
Each word, except the first, starts
with a capital letter:
myVariableName = "John"
Each word starts with a capital
letter:
MyVariableName = "John"
Each word is separated by an
underscore character:
my_variable_name = "John"

Variables
▸Many Values to Multiple Variables
-Python allows you to assign values to multiple variables in one line
▸One Value to Multiple Variables
-The same value can be assigned to multiple variables in one line
▸Unpack a Collection
-If you have a collection of values in a list, tuple etc. Python allows you to extract the
values into variables. This is called unpacking.
17
Assign Multiple Values
x, y, z = "Orange", "Banana", "Cherry"
x = y = z = "Orange"
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits

Input and Output
▸Using print() function for print value(s)/variable(s) to standard device
▸Output formatting in Python with various techniques including
-the format() method,
-manipulation of the sep and end parameters,
-f-strings, and
-the versatile % operator.
▸These methods enable precise control over how data is displayed,
enhancing the readability and effectiveness of your Python programs.
18
Output
name, age = "Alice", 30
print("Name:", name, "Age:", age) # ->Name: Alice Age: 30
amount = 150.75
print("Amount:
${:.2f}".format(amount)) # Amount:
$150.75
# end Parameter with '@'
print("Python", end='@') # Python@is great!
print("is great!")
# Separating with Comma
print('X', 'Y', 'Z', sep='_') # X_Y_Z
# another example
print('vovanhai', 'ueh.edu.vn', sep='@') # [email protected]
print("Hello python's world")

Input and Output
▸Using f-string (discuss later)
▸Using % Operator: We can use ‘%’ operator. % values are replaced with
zero or more value of elements. The formatting using % is similar to that
of ‘printf’ in the C programming language.
-%d –integer
-%f – float
-%s – string
-%x –hexadecimal
-%o – octal
19
Output
name, age = 'Teo', 23
print(f"Hello, My name is {name} and I'm {age} years old.")
i, f, h = 10, 13.6, 365
print("i=%d, f=%f, h=%x " % (i, f, h))
# i=10, f=13.600000, h=16d

Input and Output
▸Python input() function is used to take user input. By default, it returns
the user input in form of a string.
▸Change the Type of Input
▸Taking multiple input
20
Input
# Taking input from the user
num = int(input("Enter a value: "))
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)

Variables
1.Create a variable named car_name and assign the value Volvo to it.
2.Create a variable named x and assign the value 50 to it.
3.Display the sum of 5 + 10, using two variables: x and y.
4.Create a variable called z, assign x + y to it, and display the result.
5.Insert the correct syntax to assign values to multiple variables in one
line:
6.Check the data type of all your variables using type() built-in function
7.Run help('keywords') in Python shell or in your file to check for the
Python reserved words or keywords
21
Exercises

Basic Data Types
22

Data Types
▸Variables can store data of different types, and different types can do different
things.
▸Python has the following data types built-in by default, in these categories:
▸Getting the Data Type
23
Built-in Data Types
Category Type
Text Type: str
Numeric Types: int,float,complex
Sequence Types: list,tuple,range
Mapping Type: dict
Set Types: set,frozenset
Boolean Type: bool
Binary Types: bytes,bytearray,memoryview
None Type: NoneType
x = 5
print(type(x)) # result: <class 'int'>

Data Types
▸In Python, the data type is set when you assign a value to a variable:
24
Setting the Data Types
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Data Types
▸If you want to specify the data type, you can use the following
constructor functions:
25
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

Numbers
▸There are three numeric types in Python:
-int
-float
-complex
▸Variables of numeric types are created when you assign a value to them:
▸You can convert from one type to another with the int(), float(), and
complex() methods:
26
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
# Complex
x = 3 + 5j # <class 'complex'>
y = 5j
z = -5j
# Float
x = 1.10 # <class 'float'>
y = 1.0
z = -35.59
# Int
x = 1 # <class 'int'>
y = 35656222554887711
z = -3255522
x = 1 # int
y = 2.8 # float
z = 1j # complex
# convert from int to float:
a = float(x)
# convert from float to int:
b = int(y)
# convert from int to complex:
c = complex(x)
Random number
import random
print(random.randrange(1, 10))

Numbers
▸A variable can be specified with a type by using casting.
▸Casting in python is therefore done using constructor functions:
-int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
-float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
-str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
▸Examples
27
Specify a Variable Type
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Numbers
1.Declare 5 as num_one and 4 as num_two
a)Add num_one and num_two and assign the value to a variable total
b)Subtract num_two from num_one and assign the value to a variable diff
c)Multiply num_two and num_one and assign the value to a variable product
d)Divide num_one by num_two and assign the value to a variable division
e)Use modulus division to find num_two divided by num_one and assign the value to
a variable remainder
f)Calculate num_one to the power of num_two and assign the value to a variable
exp
g)Find floor division of num_one by num_two and assign the value to a variable
floor_division
2.The radius of a circle is 30 meters.
a)Calculate the area of a circle and assign the value to a variable name of
area_of_circle
b)Calculate the circumference of a circle and assign the value to a variable name of
circum_of_circle
c)Take radius as user input and calculate the area.
28
Exercises

Strings
▸Strings in python are surrounded by either single quotation marks, or
double quotation marks.
-'hello' is the same as "hello".
▸It is possible to use quotes inside a string, if they don't match the quotes
surrounding the string:
▸You can assign a multiline string to a variable by using three quotes:
▸Strings in Python are arrays of bytes representing unicode characters.
The square brackets [] can be used to access elements of the string.
▸To get the length of a string, use the len() function.
29
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
a = """Lorem ipsum dolor sit amet,
ut labore et dolore magna aliqua."""
a = '''Lorem ipsum dolor sit amet,
ut labore et dolore magna aliqua.'''
a = "Hello, World!"
print(a[1])
a = "Hello, World!"
print(len(a))
# Loop through the letters in a string
for x in "life is a present":
print(x)
x = 'life is a present'
for i in range(len(x)):
print(x[i])

Strings
▸You can return a range of characters by using the slice syntax.
-Specify the start index and the end index, separated by a colon, to return a part of
the string.
-By leaving out the start index, the range will start at the first character:
-By leaving out the end index, the range will go to the end:
-Use negative indexes to start the slice from the end of the string:
30
Slicing Strings
# Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5]) # --> llo
# Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5]) # Hello
# Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:]) # llo, World!
# From: "o" in "World!" (position -5)
# To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2]) # orl

Strings
▸The upper() and lower() methods return the string in upper case and lower case:
▸The strip() method removes any whitespace from the beginning or the end:
▸The replace() method replaces a string with another string:
▸The split() method returns a list where the text between the specified separator
becomes the list items
▸PythonStringMethods
31
Modify Strings
a = "Hello, World!"
print(a.upper())
print(a.lower())
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
a = "Hello, World!"
print(a.replace("H", "J")) # Jello, World!
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Read more: https://www.digitalocean.com/community/tutorials/python-string-functions

Strings
▸we cannot combine strings and numbers like this:
▸The F-String can be used to format string with placeholders
-To specify a string as an f-string, simply put an f in front of the string literal and add
curly brackets {} as placeholders for variables and other operations.
-A placeholder can contain variables, operations, functions, and modifiers to format
the value.
-It can be used for formatting the number
-Or, using with an expression
32
String Format
age = 36
txt = "My name is John, I am " + age
print(txt)
price = 59
txt = f"The price is {price} dollars" # -> The price is 59 dollars
price = 59.678
txt = f"The price is {price:.2f} dollars" # ->The price is 59.68 dollars
txt = f"The price is {13 * 59} dollars" # The price is 767 dollars
# Return "Expensive" if the price is over 50, otherwise return "Cheap":
price = 49
txt = f"It is very {'Expensive' if price > 50 else 'Cheap

Strings
▸Formatting types
33
String Format (continue)
:< Left aligns the result (within the available space)
:> Right aligns the result (within the available space)
:^ Center aligns the result (within the available space)
:= Places the sign to the left most position
:+ Use a plus sign to indicate if the result is positive or negative
:- Use a minus sign for negative values only
: Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:, Use a comma as a thousand separator
:_ Use a underscore as a thousand separator
:b Binary format
:c Converts the value into the corresponding Unicode character
:d Decimal format
:e Scientific format, with a lower-case e
:E Scientific format, with an upper-case E
:f Fix point number format
:F Fix point number format, in uppercase format (showinfandnanasINFandNAN)
:g General format
:G General format (using a upper case E for scientific notations)
:o Octal format
:x Hex format, lower case
:X Hex format, upper case
:n Number format
:% Percentage format
price = 59000
txt = f"The price is {price:,} dollars" # -> The price is 59,000 dollars

Strings
▸The format() method can be used to format strings (before v3.6), but f-
strings are faster and the preferred way to format strings.
▸You can use index numbers :
▸You can also use named indexes:
34
String Format (continue)
quantity = 3
item_no = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, item_no, price))
# -> I want 3 pieces of item number 567 for 49.00 dollars.
age, name = 36, "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name)) # His name is John. John is 36 years old.
my_order = "I have a {car_name}, it is a {model}."
print(my_order.format(car_name="Ford", model="Mustang"))
# ->I have a Ford, it is a Mustang.

Strings
▸To insert characters that are illegal in a string, use an escape character.
▸An escape character is a backslash \ followed by the character you want
to insert.
35
Escape characters
txt = "We are the so-called \"Vikings\" from the north."
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

Strings
Give: x = "Hello World“
1.Use the len function to print the length of the string.
2.Get the characters from index 2 to index 4 (llo).
3.Return the string without any whitespace at the beginning or the end.
4.Convert the value of txt to upper/lower case.
5.Replace the character l with a L.
6.Enter a string prompt keyboard then display it reverse order
36
Exercises

Booleans
▸In programming you often need to know if an expression is True or False.
-You can evaluate any expression in Python, and get one of two answers, True or
False.
-When you compare two values, the expression is evaluated, and Python returns the
Boolean answer:
▸The bool() function allows you to evaluate any value and give you True or
False in return. Almost any value is evaluated to True if it has some sort
of content.
-Any string is True, except empty strings.
-Any number is True, except 0.
-Any list, tuple, set, and dictionary are True, except empty ones.
▸There are not many values that evaluate to False, except empty values,
such as (), [], {}, "", the number 0, and the value None.
-The value False evaluates to False.
37
print(10 > 9) # ->True
print(10 == 9) # ->False
print(10 < 9) # ->False
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Operators
38

Operators
▸Operators are used to perform operations on variables and values.
▸Python divides the operators in the following groups:
-Arithmetic operators
-Assignment operators
-Comparison operators
-Logical operators
-Identity operators
-Membership operators
-Bitwise operators
39
OperatorName Example
+ Addition x + y
- Subtraction x - y
* Multiplicationx * y
/ Division x / y
% Modulus x % y
** Exponentiationx ** y
// Floor divisionx // y
OperatorName Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal tox >= y
<= Less than or equal tox <= y
Arithmetic Operators
Comparison Operators

Operators
40
OperatorExample 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)
Assignment Operators
Logical Operators
OperatorDescription Example
and Returns True if both
statements are true
x < 5 and x < 10
or Returns True if one of the
statements is true
x < 5 or x < 4
not Reverse the result, returns
False if the result is true
not(x < 5 and x <
10)
OperatorDescription Example
is Returns True if both variables
are the same object
x is y
is notReturns True if both variables
are not the same object
x is not y
Identity Operators
OperatorDescription Example
in Returns True if a sequence with the specified value is
present in the object
x in y
not in Returns True if a sequence with the specified value is
not present in the object
x not in y
Membership Operators

Operators
41
OperatorName Description Example
& AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left
shift
Shift left by pushing zeros in from the right and let the leftmost
bits fall off
x << 2
>> Signed right
shift
Shift right by pushing copies of the leftmost bit in from the left,
and let the rightmost bits fall off
x >> 2
Bitwise Operators

Operators
▸Operator precedence describes the order in which operations are
performed.
▸The precedence order is described in the table below, starting with the
highest precedence at the top:
42
Operator Precedence
Operator Description
() Parentheses
** Exponentiation
+x-x~x Unary plus, unary minus, and bitwise NOT
*///% Multiplication, division, floor division, and modulus
+- Addition and subtraction
<<>> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==!=>>=<<=isis notinnot in Comparisons, identity, and membership operators
not Logical NOT
and AND
or OR

Operators
1.Write a program that prompts the user to enter base and height of the
triangle and calculate an area of this triangle (area = 0.5 x b x h).
2.Write a script that prompts the user to enter side a, side b, and side c of the
triangle. Calculate the perimeter of the triangle (perimeter = a + b + c).
3.Get length and width of a rectangle using prompt. Calculate its area (area =
length x width) and perimeter (perimeter = 2 x (length + width))
4.Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and
circumference (c = 2 x pi x r) where pi = 3.14.
5.Calculate the slope, x-intercept and y-intercept of y = 2x -2
6.Slope is (m = y2-y1/x2-x1). Find the slope and Euclidean distance between
point (2, 2) and point (6,10)
7.Compare the slopes in tasks 8 and 9.
8.Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and
figure out at what x value y is going to be 0.
9.Find the length of 'python' and 'dragon' and make a falsy comparison
statement.
43
Exercises

Operators
10.Use and operator to check if 'on' is found in both 'python' and 'dragon'
11.I hope this course is not full of jargon. Use in operator to check if jargon
is in the sentence.
12.There is no 'on' in both dragon and python
13.Find the length of the text python and convert the value to float and
convert it to string
14.Even numbers are divisible by 2 and the remainder is zero. How do you
check if a number is even or not using python?
15.Writs a script that prompts the user to enter hours and rate per hour.
Calculate pay of the person?
16.Write a script that prompts the user to enter number of years.
Calculate the number of seconds a person can live. Assume a person
can live hundred years
44
Exercises

Python Flow Control
45

Conditional Statements
▸In computer programming, the if statement is a conditional statement. It
is used to execute a block of code only when a specific condition is met.
▸Types of Control Flow in Python
-Python If Statement
-Python If Else Statement
-Python Nested If Statement
-Python Elif
-Ternary Statement (Short Hand If Else Statement)
46
Introduction

Python if...else Statement
47
Python if Statement - Example
▸Syntax
if (condition):
# code for execution
# when the condition's result is True
number = int(input('Enter a number: ‘))
# check if number is greater than 0
if number > 0:
print(f'{number} is a positive number.’)
print('A statement outside the if statement.')

Python if...else Statement
▸Syntax
48
Python if...else Statement
if condition:
# body of if statement
else:
# body of else statement
number = int(input('Enter a number: '))
if number > 0:
print('Positive number')
else:
print('Not a positive number')
print('This statement always executes')

Python if...else Statement
▸Syntax
49
The if…elif…else Statement
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
number = -5
if number > 0:
print('Positive number')
elif number < 0:
print('Negative number')
else:
print('Zero')
print('This statement is always executed')

Python if...else Statement
50
Nested if Statements
number = 5
# outer if statement
if number >= 0:
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')

Python if...else Statement
▸If you have only one statement to execute, one for if, and one for else,
you can put it all on the same line:
▸Syntax:
▸Example
51
Compact if (Ternary If Else) Statement
do_work if condition else do_other_work
a = 30
b = 330
print("A") if a > b else print("B")
print("A") if a > b else print("=") if a == b else print("B")

Python if...else Statement
1.Write a program to check a person is eligible for voting or not (saccept
age from user)
2.Write a program to check whether a number entered by user is even or
odd.
3.Write a program to check whether a number is divisible by 7 or not.
4.Write a program to check the last digit od a number (entered by user)
is divisible by 3 or not.
5.Write a Python program to guess a number between 1 and 9.
6.Write a program to accept a number from 1 to 7 and display the name
of the day like 1 for Sunday, 2 for Monday and so on.
52
Exercises

The For loop Statement
53

For loop Statement
▸A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
▸Syntax
54
for var in sequence:
# statements
languages = ['Swift', 'Python', 'Go']
# access elements of the list one by one
for lang in languages:
print(lang)
Theforloop iterates over the elements
ofsequencein order. In each iteration, the
body of the loop is executed.
language = 'Python'
# iterate over each character in language
for x in language:
print(x)
# iterate from i = 0 to i = 3
for i in range(4):
print(i)

For loop Statement
▸A for loop can have an optional else clause. This else clause executes
after the iteration completes.
▸Note: The else block will not execute if the for loop is stopped by a break
statement.
▸Python for loop in One Line
55
Python for loop with else clause
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Numbers =[x for x in range(11)]
print(Numbers)

For loop Statement
▸A for loop can also have another for loop inside it.
▸For each cycle of the outer loop, the inner loop completes its entire
sequence of iterations.
56
Nested for loops
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(f"i = {i}, j = {j}")

For loop Statement
▸Continue in Python For Loop
-Python continue Statement returns the control to the beginning of the loop.
▸Break in Python For Loop
▸For Loop in Python with Pass Statement
57
Control Statements with For Loop
for letter in 'university of economics HCMC':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
for letter in 'University of economics HCMC':
# break the loop as soon it sees 'e' or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter) # --> e
# An empty loop
for letter in 'University of economics HCMC':
pass
print('Last Letter :', letter)

For loop Statement
1.write a program that prints numbers from 1 to 10
2.Write a program to calculate the sum of numbers in a range from 1 to n (n is
entered from the keyboard)
3.Write a program to calculate the sum of even (/odd) numbers in a range from
1 to n (n is entered from the keyboard)
4.Write a program to check how many vowels are in a string entered from the
keyboard.
5.Write a program to count the number of words in a sentence the user enters.
6.Write a program that implements a game as the following description:
7. 1. The computer generates a random number from 1 to 100
8. 2. The user was asked to guess
9. 3. match the user-guessing number to the generated number
10.The user can only guess five times.
58
Exercises

Python while Loop
59

Python while Loop
▸In Python, a while loop can be used to repeat a block of code until a
certain condition is met.
▸Syntax:
60
while condition:
# body of while loop
# Print numbers until the user enters 0
number = int(input('Enter a number: '))
# iterate until the user enters 0
while number != 0:
print(f'You entered {number}.')
number = int(input('Enter a number: '))
print('The end.')

Python while Loop
▸If the condition of a while loop always evaluates to True, the loop runs
continuously, forming an infinite while loop.
61
Infinite while Loop
age = 28
# the test condition is always True
while age > 19:
print('Infinite Loop')
# Initialize a counter
count = 0
# Loop infinitely
while True:
# Increment the counter
count += 1
print(f"Count is {count}")
# Check if the counter has reached a certain value
if count == 10:
# If so, exit the loop
break
# This will be executed after the loop exits
print("The loop has ended.")

Python while Loop
▸Python Continue Statement
returns the control to the
beginning of the loop.
▸Python Break Statement
brings control out of the
loop.
▸The Python pass statement
to write empty loops. Pass is
also used for empty control
statements, functions, and
classes.
62
Control Statements in Python while loop
# Prints all letters except 'e' and 's'
i = 0
a = 'University of Economics HCMC'
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
continue
print('Current Letter :', a[i])
i += 1
break the loop as soon it sees ‘e’ or
‘s’ if we replace the continue with
break statement
break
# An empty loop
i = 0
a = 'University of Economics HCMC'
while i < len(a):
i += 1
pass

Python while Loop
1. Guess The Number Game:
-we will generate a random number with the help of randint() function from 1 to 100
and ask the user to guess it.
-After every guess, the user will be told if the number is above or below the
randomly generated number.
-The user will win if they guess the number maximum five attempts.
-Ask the user to stop or continue playing again.
2.Write a game that simulate rolling a pair of dice.
-If the sum of two faces is greater than 5 → “Tài”
-Otherwise → “Xỉu”
-User ask for guessing “Tài” or “Xỉu”
-Match the results
-After one turn, ask user for continue playing game.
-**** Extend the game by asking the user to enter an amount of money, then
continue playing until the user runs out of money or the user stops playing. Statistics
of results.
63
Exercises

Advanced Data Types
Python Collections
64

Python Collections
▸There are four collection data types in the Python programming
language:
-List is a collection which is ordered and changeable. Allows duplicate members.
-Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
-Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
-Dictionary is a collection which is ordered** and changeable. No duplicate
members.
•*Set items are unchangeable, but you can remove and/or add items whenever
you like.
•**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
65
Introduction

Python Collections
Python List
66

List
▸Lists are used to store multiple items in a single variable.
▸Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
▸Lists are created using square brackets:
▸Characteristics
-Ordered - They maintain the order of elements.
-Mutable - Items can be changed after creation.
-Allow duplicates - They can contain duplicate values.
67
Introduction
fruit_list = ["apple", "banana", "cherry"]
fruit_list = ["apple", "banana", "cherry", "apple", "cherry"]
fruit_list.append("banana")
fruit_list.remove("cherry")
print(fruit_list) # ->['apple', 'banana', 'apple', 'cherry', 'banana']
Use the len()
function to
determine the list's
number of items.
print(len(fruit_list))

List
▸We can use the built-in list() function to convert other iterable (strings,
dictionaries, tuples, etc.) to a list.
68
Create list
x = "axz"
# convert to list
result = list(x)
print(result) # ['a', 'x', 'z']
# note the double round-brackets
fruit_list = list(("apple", "banana", "cherry"))
print(fruit_list) # ['apple', 'banana', 'cherry']

List
▸We use these index numbers to access list items.
▸Negative Indexing in Python
-Python also supports negative indexing. The index of the last element is -1, the
second-last element is -2, and so on.
69
Access List Elements
Index of List Elements
languages = ['Python', 'Swift', 'C++']
# Access the first element
print(languages[0]) # Python
# Access the third element
print(languages[2]) # C++
languages = ['Python', 'Swift', 'C++']
# Access item at index 0
print(languages[-1]) # C++
# Access item at index 2
print(languages[-3]) # Python

List
▸It is possible to access a section of items from the list using the slicing
operator :
70
Slicing of a list
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
# items from index 2 to index 4
print(my_list[2:5]) # ->['o', 'g', 'r']
# items from index 5 to end
print(my_list[5:]) # ->['a', 'm']
# items beginning to end
print(my_list[:]) # ->['p', 'r', 'o', 'g', 'r', 'a', 'm']
Note: If the specified index does not exist in a list, Python throws the IndexError exception.

List
71
Modify a list
fruits = ['apple', 'banana', 'orange']
# using append method to add item add the end of list
fruits.append('cherry') # ['apple', 'banana', 'orange', 'cherry']
# insert 'cherry' at index 2
fruits.insert(2, 'grape') # ['apple', 'banana', 'grape', 'orange', 'cherry']
# changing the third item to ‘mango'
fruits[2] = 'mongo' # ->['apple', 'banana', ‘mango', 'orange', 'cherry']
# remove 'banana' from the list (first occurrence)
fruits.remove("banana") # ->['apple', ‘mango', 'orange', 'cherry']
# deleting the second item
del fruits[1] # ->['apple', 'orange', 'cherry']
# deleting items from index 0 to index 2
del fruits[0:2] # ->['cherry']
# the extend() method can be used to add elements to a list from other
iterables.
odd_numbers, even_numbers = [1, 3, 5], [2, 4, 6]
# adding elements of one list to another
odd_numbers.extend(even_numbers) # ->[1, 3, 5, 2, 4, 6]
print('Updated Numbers:', odd_numbers)
The list slice technique
can be used to modify
list items.
Change the values "banana" and "cherry"
with the values "blackcurrant" and
"watermelon":
fruits = ["apple", "banana", "cherry",
"orange", "kiwi", "mango"]
fruits[1:3] = ["blackcurrant", "watermelon"]

List
▸Sort the list alphanumerically
▸Sort descending (use the keyword argument reverse = True)
▸CaseInsensitiveSort
▸Thesort()vs.sorted()methods:
-The sort() method doesn’t return anything, it modifies the original list (i.e. sorts in-
place). If you don’t want to modify the original list, use sorted() function. It returns a
sorted copy of the list.
72
Sort lists
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort() # ->['banana', 'kiwi', 'mango', 'orange', 'pineapple']
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse=True) # ->['pineapple', 'orange', 'mango', 'kiwi', 'banana']
fruits = ["orange", "Mango", "kiwi", "Pineapple", "banana"]
fruits.sort() # ->['Mango', 'Pineapple', 'banana', 'kiwi', 'orange']
fruits.sort(key=str.lower) # ->['banana', 'kiwi', 'Mango', 'orange', 'Pineapple']
fruits.sort(key=len) # ->['kiwi', 'Mango', 'orange', 'banana', 'Pineapple']
new_list = sorted(fruits)
print(new_list)

List
▸DONOT copy a list by usingtheassignoperator
list2 = list1,
▸Cause: list2 will only be a reference to list1, and changes made in list1
will automatically also be made in list2.
▸Make a copy of a list
-With the copy() method
-Byusing the built-in method list()
-Byusing the : (slice) operator.
73
Copy Lists
fruits = ["apple", "banana", "cherry"]
new_list_1 = fruits.copy()
new_list_2 = list(fruits)
new_list_3 = fruits[:]

List
▸Iterating tthrough a List
▸Listmethods
74
List methods
fruits = ['apple', 'banana', 'orange']
# iterate through the list
for fruit in fruits:
print(fruit)
Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes item present at the given index
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
copy() Returns the shallow copy of the list
fruits = ["apple", "banana", "cherry"]
# looping using list comprehension
[print(x) for x in fruits]

List
Exercises
75

Python Collections
Python Tuple
76

Tuple
▸Tuples are used to store multiple items in a single variable.
▸A tuple is a collection which is ordered and unchangeable.
▸A tuple can be created by
-placing items inside parentheses ().
-usingatuple()constructor.
▸Tuple Characteristics
-Ordered - They maintain the order of elements.
-Immutable - They cannot be changed after creation(ie.Unchangeable).
-Allow duplicates - They can contain duplicate values.
77
Introduction
fruits = ("orange", "Mango", "kiwi", "Pineapple", "banana")
tuple_constructor = tuple(('Jack', 'Maria', 'David'))

Tuple
▸Each item in a tuple is associated with a number, known as a index.
-The index always starts from 0, meaning the first item of a tuple is at index 0, the
second item is at index 1, and so on.
▸Specify negative indexes if you want to start the search from the end of
the tuple:
▸Check if an Item Exists in the Tuple
78
Access Tuple Items
languages = ('Python', 'Swift', 'C++')
print(languages[1])
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
# returns the items from index -4 (included) to index -1 (excluded)
print(fruits[-4:-1]) # ->('orange', 'kiwi', 'melon')
print('grape' in fruits) # False
print('cherry' in fruits) # True

Tuple
▸Tuples are immutable(unchangeable)→cannotchangethevalues
▸Wecan convert the tuple into a list, change the list, and convert the list
back into a tuple.☺
▸Itisallowed to add tuples to tuples
▸Iteratethroughthetuple
79
Update Tuple
fruits = ("apple", "banana", "cherry")
new_fruits = ("orange", "kiwi", "melon")
fruits += new_fruits # ->('apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon')
x = ("apple", "banana", "cherry")
y = list(x)
y.remove('apple')
x = tuple(y)
print(x) # ->('banana', 'cherry')
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) # -> ('apple', 'kiwi', 'cherry')
fruits = ('apple','banana','orange')
for fruit in fruits:
print(fruit)

Tuple
▸In Python, there is a very powerful tuple assignment feature that assigns
the right-hand side of values into the left-hand side.
▸In another way, it is called unpacking of a tuple of values into a variable.
▸In packing, we put values into a new tuple while in unpacking we extract
those values into a single variable.
80
Unpacking a Tuple
characters = ("Aragorn", "Gimli", "Legolas") # python tuple packing line
(human, dwarf, elf) = characters # python tuple unpacking line
print("Human :", human)
print("Dwarf :", dwarf)
print("Elf :", elf)
characters = ("Aragorn", "Gimli", "Legolas", "Elrond", "Galadriel")
(human, dwarf, *elf) = characters
print("Human :", human)
print("Dwarf :", dwarf)
print("Elf :", elf)

Tuple
▸Check if an Item Exists in the Tuple
▸Deleting the tuple
▸Get the index of an item on Tuple
▸Count the number of times the specified element appears in the tuple.
81
Tuple methods
colors = ('red', 'orange', 'blue')
print('yellow' in colors) # False
print('red' in colors) # True
animals = ('dog', 'cat', 'rat')
del animals
vowels = ('a', 'e', 'i', 'o', 'u')
index = vowels.index('e')
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# counts the number of i's in the tuple
count = vowels.count('i') # -->2

Tuple
▸Write a Python program
-to create a tuple of numbers and print one item.
- to unpack a tuple into several variables.
- to add an item to a tuple.
- to find the index of an item in a tuple.
- to find the repeated items of a tuple
82
Exercises

Python Collections
Python Set
83

Python Set
▸A Set in Python programming is an unordered collection data type that is
iterable and has no duplicate elements.
▸sets are created by placing all the elements inside curly braces {},
separated by commas.
▸Typecasting list to set
▸Immutable set:
84
Introduction
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
Create an Empty Set
# create an empty set
empty_set = set() # type(empty_set)==> <class 'set'>
# create an empty dictionary
empty_dictionary = {} # type(empty_dictionary)==><class 'dict'>
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # ==> {8, 2, 4, 6}
# typecasting list to set
my_set = set(["a", "b", "c"])
Duplicate items in Set
my_set = {"university", "economic", "HCMC"}
# Adding element to the set
my_set.add("CTD")
# values of a set cannot be changed
my_set[1] = "Academy" # -->TypeError: 'set' object does not support item assignment

Python Set
▸Update Python Set
-The update() method is used to update the set with items other collection types
(lists, tuples, sets, etc).
▸Remove an Element from a Set
-The discard() method is used to remove the specified element from a set.
▸Frozen sets in Python are immutable objects that only support
methods and operators that produce a result without affecting the
frozen set or sets to which they are applied.
85
Update Python Set
companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
companies.update(tech_companies)
languages = {'Swift', 'Java', 'Python'}
print('Initial Set:', languages)
# remove 'Java' from a set
removedValue = languages.discard('Java')
print('Set after remove():', languages) # -->{'Python', 'Swift'}
fruits = frozenset(["apple", "banana", "orange"])
fruits.append("pink") # -->AttributeError: 'frozenset' object has no attribute 'append'

Python Set
86
Python Set Operations
A, B = {1, 3, 5}, {1, 2, 3}
print('Union using |:', A | B)
print('Union using union():', A.union(B))
print('Intersection using &:', A & B)
print('Intersection using intersection():', A.intersection(B))
print('Difference using &:', A - B)
print('Difference using difference():', A.difference(B))
print('Symmetric Difference using ^:', A ^ B)
print('Symmetric Difference using symmetric_difference():', A.symmetric_difference(B))
The intersection of two sets A and B include the common elements between set A and B.
The difference between two sets A and B include elements of set A that are not present on set B.
The symmetric difference between two sets A and B includes all elements of A and B without the
common elements.
The union of two sets A and B includes all
the elements of sets A and B.
A, B = {1, 3, 5}, {5, 3, 1}
if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')
Check if two sets are
equal

Python Set
87
Python Set methods
Method Description
issubset()
Returns True if another set
contains this set
issuperset()
Returns True if this set
contains another set
pop()
Removes and returns an
arbitrary set element. Raises
KeyError if the set is empty
remove()
Removes an element from the
set. If the element is not a
member, raises a KeyError
symmetric_difference()
Returns the symmetric
difference of two sets as a
new set
symmetric_difference_update
()
Updates a set with the
symmetric difference of itself
and another
union()
Returns the union of sets in a
new set
update()
Updates the set with the
union of itself and others
Method Description
add() Adds an element to the set
clear()
Removes all elements from
the set
copy() Returns a copy of the set
difference()
Returns the difference of two
or more sets as a new set
difference_update()
Removes all elements of
another set from this set
discard()
Removes an element from
the set if it is a member. (Do
nothing if the element is not
in set)
intersection()
Returns the intersection of
two sets as a new set
intersection_update()
Updates the set with the
intersection of itself and
another
Isdisjoint()
Returns True if two sets have
a null intersection

Python Set
1.Write a Python program to find the maximum and minimum values in a
set.
2.Write a Python program to check if a given value is present in a set or
not.
3.Write a Python program to check if two given sets have no elements in
common.
4.Write a Python program to find all the unique words and count the
frequency of occurrence from a given list of strings. Use Python set
data type.
5.Given two sets of numbers, write a Python program to find the missing
numbers in the second set as compared to the first and vice versa. Use
the Python set.
88
Exercises

Python Collections
Python Dictionary
89

Python Dictionary
▸A Python dictionary is a data structure that stores the value in key:value pairs.
▸Python dictionaries are ordered and can not contain duplicate keys.
▸Keys of a dictionary must be immutable (Immutable objects can't be changed
once created.).
▸The keys of a dictionary must be unique. If there are duplicate keys, the later
value of the key overwrites the previous value.
90
Introduction
dict_var = { key1: value1’, key2: ‘value2’, ...}
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
# printing the dictionary
print(country_capitals)
# {'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

Python Dictionary
▸Access Dictionary Items
-We can access the value of a dictionary
item by placing the key inside square
brackets.
-We can also use the get() method to access
dictionary items.
▸Add Items to a Dictionary
-We can add an item to a dictionary by
assigning a value to a new key.
▸Change Dictionary Items
-Python dictionaries are mutable
(changeable). We can change the value of a
dictionary element by referring to its key.
▸Remove Dictionary Items
-We can use the del statement to remove an
element from a dictionary.
91
Actions
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa"
}
# Access items
den_cap = country_capitals["Germany"]
can_cap = country_capitals.get("Canada")
# add an item with "Italy" as key and "Rome"
as its value
country_capitals["Italy"] = "Rome"
# change the value of "Italy" key to "Naples"
country_capitals["Italy"] = "Naples"
country_capitals.update({"Italy": "Rome"})
# delete item having "Germany" key
del country_capitals["Germany"]
# clear the dictionary
country_capitals.clear()

Python Dictionary
▸Nested dictionaries are dictionaries that are stored as values within another
dictionary.
▸Ex: An organizational chart with keys being different departments and values
being dictionaries of employees in a given department. For storing employee
information in a department, a dictionary can be used with keys being employee
IDs and values being employee names. The tables below outline the structure of
such nested dictionaries and how nested values can be accessed.
92
Nested Dictionaries
Accessing nested dictionary items
company_org_chart = {
"Marketing": {
"ID234": "Jane Smith"
},
"Sales": {
"ID123": "Bob Johnson",
"ID122": "David Lee"
},
"Engineering": {
"ID303": "Radhika Potlapally",
"ID321": "Maryam Samimi"
}
}
print(company_org_chart["Sales"]["ID122"]) # -->David Lee
print(company_org_chart["Engineering"]["ID321"]) # -->Maryam Samimi

Python Dictionary
93
Python Dictionary Methods
Method Description
dict.clear() Remove all the elements from the dictionary
dict.copy() Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
dict.items() Returns a list containing a tuple for each key value pair
dict.keys() Returns a list containing dictionary’s keys
dict.update(dict2) Updates dictionary with specified key-value pairs
dict.values() Returns a list of all the values of dictionary
pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
dict.setdefault(key,default= “None”)
set the key to the default value if the key is not specified in the
dictionary
dict.has_key(key) returns true if the dictionary contains the specified key.

Python Dictionary
1.Write python program:
a)Convert two lists into a dictionary
b)Merge two Python dictionaries into one
c)Print the value of key ‘history’ from the below dict
d)Initialize dictionary with default values
e)Create a dictionary by extracting the keys from a given dictionary
f)Delete a list of keys from a dictionary
g)Check if a value exists in a dictionary
h)Rename key of a dictionary
i)Get the key of a minimum value from the following dictionary
j)Change value of a key in a nested dictionary
2.Write a Python program that counts the number of times characters
appear in a text paragraph.
3.Write a program using a dictionary containing keys starting from 1 and
values ​​containing prime numbers less than a value N.
94
Exercises

Python Dictionary
Restructuring the company data: Suppose you have a dictionary that contains information about
employees at a company. Each employee is identified by an ID number, and their information
includes their name, department, and salary. You want to create a nested dictionary that groups
employees by department so that you can easily see the names and salaries of all employees in
each department.
Write a Python program that when given a dictionary, employees, outputs a nested dictionary,
dept_employees, which groups employees by department.
95
Exercises
# Input:
employees = {
1001: {"name": "Alice", "department": "Engineering",
"salary": 75000},
1002: {"name": "Bob", "department": "Sales", "salary":
50000},
1003: {"name": "Charlie", "department": "Engineering",
"salary": 80000},
1004: {"name": "Dave", "department": "Marketing",
"salary": 60000},
1005: {"name": "Eve", "department": "Sales", "salary":
55000}
}
# Resulting dictionary:
dept_employees = {
"Engineering": {
1001: {"name": "Alice", "salary": 75000},
1003: {"name": "Charlie", "salary": 80000}
},
"Sales": {
1002: {"name": "Bob", "salary": 50000},
1005: {"name": "Eve", "salary": 55000}
},
"Marketing": {
1004: {"name": "Dave", "salary": 60000}
}
}

Summary
97

Thanks for your listening!
98
Tags