0% found this document useful (0 votes)
24 views

Python Part1 Fundamental UEH

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Part1 Fundamental UEH

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Python for Data Science

Part 1: Fundamentals

1
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).

Source: Chicken Soup for the Soul

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

3
Introduction to

4
5
History
▸ Started by Guido Van Rossum as a hobby
▸ Now widely spread
▸ Open Source! Free!
▸ Versatile

The designer of Python,


Guido van Rossum, at OSCON
2006 (src: wikipedia)

Source: unstop.com

6
Programming Languages of 2024

Source: https://www.simform.com/blog/top-programming-languages/
7
Start with python
▸ Install Python
- https://www.python.org/
▸ Python tutorial
- https://docs.python.org/3/tutorial/
- …
- Ask google
▸ IDEs

8
Your First Python Program

10
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
# This is a comment
print("Hello, World!") # This is a
comment

▸ Multiline Comments

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

11
Variables
Python as a calculator
▸ 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

12
Variables
▸ Variables are containers for storing data values.
x=5
▸ Creating Variables y = "John"
print(x)
- Python has no command for declaring a variable.
print(y)
- 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. 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))
14
Variables
Variable Names
▸ 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:

Camel Case Pascal Case Snake Case


Each word, except the first, starts Each word starts with a capital Each word is separated by an
with a capital letter: letter: underscore character:
myVariableName = "John" MyVariableName = "John" my_variable_name = "John"

15
Variables
Assign Multiple Values
▸ Many Values to Multiple Variables
- Python allows you to assign values to multiple variables in one line

x, y, z = "Orange", "Banana",
"Cherry"
▸ One Value to Multiple Variables
- The same value can be assigned to multiple variables in one line

x = y = z = "Orange"

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

fruits = ["apple", "banana",


"cherry"]
x, y, z = fruits
16
Input and Output
Output
▸ Using print() function for print value(s)/variable(s) to standard device
name, age = "Alice", 30
print("Hello python's
print("Name:", name, "Age:", age) # ->Name: Alice
world")
Age: 30
▸ 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.
# end Parameter with '@'
amount = 150.75 print("Python", end='@') # Python@is great!
print("Amount: $ print("is great!")
{:.2f}".format(amount)) # # Separating with Comma
Amount: $150.75 print('X', 'Y', 'Z', sep='_') # X_Y_Z
# another example
print('vovanhai', 'ueh.edu.vn', sep='@') #
[email protected]

17
Input and Output
Output
▸ Using f-string (discuss later)
name, age = 'Teo', 23
print(f"Hello, My name is {name} and I'm {age}
years old.")

▸ 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
i, f, h = 10, 13.6, 365
- %f – float
print("i=%d, f=%f, h=%x " % (i,
- %s – string f, h))
- %x –hexadecimal # i=10, f=13.600000, h=16d
- %o – octal

18
Input and Output
Input
▸ Python input() function is used to take user input. By default, it returns
the user
nameinput in form ofyour
= input("Enter a string.
name: ")
print("Hello,", name, "!
Welcome!")

▸ Change the Type of Input


# Taking input as int
# Typecasting to int # Taking input from the user
n = int(input("How many roses?: num = int(input("Enter a
")) value: "))
print(n)

▸ Taking multiple input


# taking two inputs at a time
x, y = input("Enter two values:
").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

19
Variables
Exercises
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

20
Basic Data Types

21
Data Types
Built-in 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:
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
▸ Getting the Data Type print(type(x)) # result: <class 'int'>

22
Data Types
Setting the Data Types
▸ In Python, the data type is set when you assign a value to a variable:
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

23
Data Types
Setting the Specific Data Type
▸ If you want to specify the data type, you can use the following
constructor functions:
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

24
Numbers
▸ There are three numeric types in Python:
- int x = 1 # int print(type(x))
- float y = 2.8 # float print(type(y))
- complex z = 1j # complex print(type(z))

▸ Variables of numeric types are created when you assign a value to them:
# Int # Float # Complex
x = 1 # <class 'int'> x = 1.10 # <class x = 3 + 5j # <class
y= 'float'> 'complex'>
35656222554887711 y = 1.0 y = 5j
z = -3255522 z = -35.59 z = -5j

▸ You can convert from one type to another with the int(), float(), and
complex() methods:
x = 1 # int # convert from float to int: Random number
y = 2.8 # float b = int(y) import random
z = 1j # complex
# convert from int to print(random.randrange(1,
# convert from int to complex: 10))
float: c = complex(x)
a = float(x)

25
Numbers
Specify a Variable Type
▸ 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
x = float(1) # x will be 1.0 x = int(1) # x will be
x = int(1) # x will be 1
y = float(2.8) # y will be
1 y = int(2.8) # y will
2.8
y = int(2.8) # y will be 2
z = float("3") # z will be
be 2 z = int("3") # z will
3.0
z = int("3") # z will be 3
w = float("4.2") # w will
be 3
be 4.2

26
Numbers
Exercises
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.

27
Strings
▸ Strings in python are surrounded by either single quotation marks, or
double quotation marks.
- 'hello' is the same as "hello".
print("It's
▸ It is possible to use quotes inside alright")
a string, if they don't match the quotes
print("He is called
surrounding the string: 'Johnny'")
print('He is called
"Johnny"')
▸ You
a =can assign ipsum
"""Lorem a multiline
dolorstring
sit to aavariable by using
= '''Lorem ipsumthree
dolorquotes:
sit
amet, amet,
ut labore et dolore magna ut labore et dolore magna
aliqua.""" aliqua.'''

▸ Strings in Python are arrays of bytes representing unicode characters. The


a = "Hello, # Loop through the letters in a
square brackets
World!"
[] can be used to access elements of the string.
string
print(a[1]) for x in "life is a present":
print(x)
x = 'life is a present'
a =get
▸ To "Hello, World!" for i in range(len(x)):
the length of a string, use the len() function. print(x[i])
print(len(a))

28
Strings
Slicing 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. # Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!"
print(b[2:5]) # --> llo
- By leaving out the start index, the range will start at the first character:
# Get the characters from the start to position 5 (not
included):
b = "Hello, World!"
print(b[:5]) # Hello

- By leaving out the end index, the range will go to the end:
# Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:]) # llo, World!

- Use negative indexes to start the slice from the end of the string:
# From: "o" in "World!" (position -5)
# To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2]) # orl
29
Strings
Modify Strings
▸ The upper() and lower() methods return the string in upper case and lower case:
a = "Hello, World!"
print(a.upper())
print(a.lower())

▸ The strip() methodaremoves


="
any whitespace
Hello, World! "
from the beginning or the end:
print(a.strip()) # returns "Hello,
World!"
▸ The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J")) # Jello,
World!

▸ The split() method returns a list where the text between the specified separator
becomes the list items
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', '
World!']

▸ Python String
Read more: Methods
https://www.digitalocean.com/community/tutorials/python-string-functions

30
Strings
String Format
▸ we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)

▸ 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. price = 59
txt = f"The price is {price} dollars" # -> The price is
59 dollars
- It can be used for formatting the number
price = 59.678
txt = f"The price is {price:.2f} dollars" # ->The price is
59.68 dollars
# Return "Expensive" if the price is over 50, otherwise return
- Or, using with an expression "Cheap":
price = 49
txt = f"It is very {'Expensive' if price > 50 else 'Cheap
txt = f"The price is {13 * 59} dollars" # The price is
767 dollars
31
Strings
String Format (continue)price = 59000
▸ Formatting types txt = f"The price is {price:,} dollars" # -> The price is 59,000 dol

:< 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 (show inf and nan as INF and NAN)
: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

32
Strings
String Format (continue)
▸ The format() method can be used to format strings (before v3.6), but f-
strings are faster and the preferred way to format strings.
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.
▸ You can use index numbers :
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.
▸ You can also use named indexes:
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.

33
Strings
Escape characters
▸ 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.
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

34
Strings
Exercises
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

35
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:
print(10 > 9) # ->True
print(10 == 9) # ->False
print(10 < 9) # ->False

▸ 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. bool("abc")
- Any string is True, except empty strings. bool(123)
bool(["apple", "cherry", "banana"])
- 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. bool("")
- The value False evaluates to False. bool(False) bool(())
bool(None) bool([])
bool(0) bool({})
36
Operators

37
Operators
▸ Operators are used to perform operations on variables and values.
▸ Python divides the operators in the following groups:
- Arithmetic operators Operator Name Example
- Assignment operators + Addition x+y
- Comparison operators - Subtraction x-y
* Multiplication x*y
- Logical operators / Division x/y
- Identity operators % Modulus x%y
- Membership operators ** Exponentiation x ** y
- Bitwise operators // Floor division x // y
Arithmetic Operators
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
Comparison Operators
<= Less than or equal to x <= y

38
Operators Logical Operators
Assignment Operators Operator Description Example
Operator Example Same As and Returns True if both x < 5 and x < 10
= x=5 x=5 statements are true
+= x += 3 x=x+3
-= x -= 3 x=x-3 or Returns True if one of the x < 5 or x < 4
*= x *= 3 x=x*3 statements is true
/= x /= 3 x=x/3 not Reverse the result, returns not(x < 5 and x <
%= x %= 3 x=x%3 False if the result is true 10)
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3 Identity Operators
&= x &= 3 x=x&3 Operator Description Example
|= x |= 3 x=x|3 is Returns True if both variables x is y
^= x ^= 3 x=x^3 are the same object
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3 is not Returns True if both variables x is not y
:= print(x := 3) x=3 are not the same object
print(x)

Operator Description Example


in Returns True if a sequence with the specified value is x in y
Membership Operators
present in the object
not in Returns True if a sequence with the specified value is x not in y
not present in the object

39
Operators
Bitwise Operators
Operator Name 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 left by pushing zeros in from the right and let the leftmost x << 2
shift bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, x >> 2
shift and let the rightmost bits fall off

40
Operators
Operator Precedence
▸ 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:
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
== != > >= < <= is is not in not in Comparisons, identity, and membership operators
not Logical NOT
and AND
or OR

41
Operators
Exercises
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. 42
Operators
Exercises
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

43
Python Flow Control

44
Conditional Statements
Introduction
▸ 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)

45
Python if...else Statement
Python if Statement - Example
▸ Syntax number = int(input('Enter a number: ‘))

# check if number is greater than 0


condition): if number > 0:
print(f'{number} is a positive
# code for execution
number.’)
# when the condition's result is True
print('A statement outside the if
statement.')

46
Python if...else Statement
Python if...else Statement
▸ Syntax
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')

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

48
Python if...else Statement
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')

49
Python if...else Statement
Compact if (Ternary 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:
do_work if condition else do_other_work
▸ Example

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

50
Python if...else Statement
Exercises
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.

51
The For loop Statement

52
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 The for loop iterates over the
for var in sequence:elements of sequence in order. In
# statements each iteration, the body of the
loop is executed.
languages = ['Swift', 'Python', 'Go']
# access elements of the list one by one
for lang in languages:
print(lang)

language = 'Python'
# iterate over each character in languag
for x in language:
print(x)
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
53
For loop Statement
Python for loop with else clause
▸ A for loop can have an optional else clause. This else clause executes
after the iteration completes.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

▸ Note: The else block will not execute if the for loop is stopped by a break
statement.

▸ Python for loop in One Line Numbers =[x for x in range(11)]


print(Numbers)

54
For loop Statement
Nested for loops
▸ 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.
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(f"i = {i}, j = {j}")

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

58
Python while Loop

▸ In Python, a while loop can be used to repeat a block of code until a


certain condition is met.
▸ Syntax: 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.')

59
Python while Loop
Infinite while Loop
▸ If the condition of a while loop always evaluates to True, the loop runs
continuously, forming an infinite while loop.

ge = 28 # Initialize a counter
# the test condition is always Truecount = 0
while age > 19: # Loop infinitely
print('Infinite Loop') 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.")

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

62
Advanced Data Types
Python Collections

63
Python Collections
Introduction
▸ 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.

64
Python Collections
Python List

65
List
Introduction
▸ 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:
fruit_list = ["apple", "banana", "cherry"] Use the len()
function to
▸ Characteristics determine the list's
- Ordered - They maintain the order of elements. number of items.
- Mutable - Items can be changed after creation.
print(len(fruit_list))
- Allow duplicates - They can contain duplicate values.
fruit_list = ["apple", "banana", "cherry", "apple",
"cherry"]
fruit_list.append("banana")
fruit_list.remove("cherry")

print(fruit_list) # ->['apple', 'banana', 'apple', 'cherry',


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

67
List
Access List Elements

Index of List Elements

▸ We use these index numbers to access list items.


languages = ['Python', 'Swift', 'C++
# Access the first element
print(languages[0]) # Python
# Access the third element
print(languages[2]) # C++

▸ 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.
languages = ['Python', 'Swift', 'C++']
# Access item at index 0
print(languages[-1]) # C++
# Access item at index 2
print(languages[-3]) # Python

68
List
Slicing of a list
▸ It is possible to access a section of items from the list using the slicing
operator :
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.

69
List
Modify a list
= ['apple', 'banana', 'orange']
ng append method to add item add the end of list
The list slice technique
append('cherry') # ['apple', 'banana', 'orange', 'cherry'] can be used to modify
list items.
ert 'cherry' at index 2
insert(2, 'grape') # ['apple', 'banana', 'grape', 'orange', 'cherry']

anging the third item to ‘mango'


Change the values "banana" and "cherry"
[2] = 'mongo' # ->['apple', 'banana', ‘mango', 'orange', 'cherry']
with the values "blackcurrant" and
move 'banana' from the list (first occurrence) "watermelon":
remove("banana") # ->['apple', ‘mango', 'orange', 'cherry']fruits = ["apple", "banana",
"cherry", "orange", "kiwi",
eting the second item "mango"]
uits[1] # ->['apple', 'orange', 'cherry'] fruits[1:3] = ["blackcurrant",
"watermelon"]
eting items from index 0 to index 2
uits[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)

70
List
Sort lists
▸ Sort the list alphanumerically
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort() # ->['banana', 'kiwi', 'mango', 'orange', 'pineapple']
▸ Sort descending (use the keyword argument reverse = True)
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse=True) # ->['pineapple', 'orange', 'mango', 'kiwi', 'banana']
▸ Case Insensitive Sort
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']

▸ The sort() 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.
new_list = sorted(fruits)
print(new_list)

71
List
Copy Lists
▸ DO NOT copy a list by using the assign operator
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
- By using the built-in method list()
- By using the : (slice) operator.

fruits = ["apple", "banana", "cherry"]


new_list_1 = fruits.copy()
new_list_2 = list(fruits)
new_list_3 = fruits[:]

72
List
List methods
▸ Iterating tthrough a List
fruits = ['apple', 'banana', 'orange'] fruits = ["apple", "banana", "cherry"]
# iterate through the list # looping using list comprehension
for fruit in fruits: [print(x) for x in fruits]
print(fruit)
▸ List methods
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

73
List
Exercises

74
Python Collections
Python Tuple

75
Tuple
Introduction
▸ 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 ().
fruits = ("orange", "Mango", "kiwi", "Pineapple", "banana")

- using a tuple() constructor.


tuple_constructor = tuple(('Jack', 'Maria', 'David'))

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

76
Tuple
Access Tuple Items
▸ 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.

languages = ('Python', 'Swift',


'C++')
print(languages[1])

▸ Specify negative indexes if you want to start the search from the end of
the tuple:
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')
▸ Check if an Item Exists in the Tuple print('grape' in fruits) #
False
print('cherry' in fruits) #
True
77
Tuple
Update Tuple
▸ Tuples are immutable (unchangeable) cannot change the values
▸ We can convert the tuple into a list, change the list, and convert the list
back into a tuple. 
x = ("apple", "banana", x = ("apple", "banana",
"cherry") "cherry")
y = list(x) y = list(x)
y[1] = "kiwi" y.remove('apple')
x = tuple(y) x = tuple(y)
print(x) # -> ('apple', 'kiwi', print(x) # ->('banana',
'cherry') 'cherry')
▸ It is allowed to add tuples to tuples
fruits = ("apple", "banana", "cherry")
new_fruits = ("orange", "kiwi", "melon")
fruits += new_fruits # ->('apple', 'banana', 'cherry', 'orange',
'kiwi', 'melon')

▸ Iterate through the tuplefruits = ('apple','banana','orange')


for fruit in fruits:
print(fruit)

78
Tuple
Unpacking a 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.
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)

79
Tuple
Tuple methods
▸ Check if an Item Exists in the Tuple
colors = ('red', 'orange',
'blue')
print('yellow' in colors) #
False
print('red' in colors) # True
▸ Deleting the tuple animals = ('dog', 'cat',
'rat')
del animals
▸ Get the index of an item on Tuple
vowels = ('a', 'e', 'i', 'o', 'u')
index = vowels.index('e')

▸ Count the number of times the specified element appears in the tuple.
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# counts the number of i's in the
tuple
count = vowels.count('i') # -->2

80
Tuple
Exercises
▸ 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

81
Python Collections
Python Set

82
Python Set
Introduction
▸ 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. Create an Empty Set
# create a set of integer type # create an empty set
student_id = {112, 114, 116, 118, 115} empty_set = set() # type(empty_set)==> <class 'set'>
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'} # create an empty dictionary
# create a set of mixed data types empty_dictionary = {} # type(empty_dictionary)==><class 'd
mixed_set = {'Hello', 101, -2, 'Bye'}
Duplicate items in Set
▸ Typecasting list to set# typecasting list to set numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # ==> {8,
my_set = set(["a", "b", "c"])
2, 4, 6}

my_set = {"university", "economic", "HCMC"}


▸ Immutable set: element to the set
# Adding
my_set.add("CTD")
# values of a set cannot be changed
my_set[1] = "Academy" # -->TypeError: 'set' object does not support item assignme

83
Python Set
Update Python Set
▸ Update Python Set
- The update() method is used to update the set with items other collection types
(lists, tuples, sets, etc).companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
companies.update(tech_companies)
▸ Remove an Element from a Set
- The discard() method is used to remove the specified element from a set.
languages = {'Swift', 'Java', 'Python'}
print('Initial Set:', languages)
# remove 'Java' from a set
removedValue = languages.discard('Java')
print('Set after remove():', languages) # -->{'Python', 'Swift'}

▸ 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.
fruits = frozenset(["apple", "banana", "orange"])
fruits.append("pink") # -->AttributeError: 'frozenset' object has no attribute 'appen

84
Python Set
Python Set Operations
A, B = {1, 3, 5}, {1, 2, 3}

print('Union using |:', A | B)


The union of two sets A and B includes all
print('Union using union():', A.union(B))
the elements of sets A and B.

The intersection of two sets A and B include the common elements between set A and B.
print('Intersection using &:', A & B)
print('Intersection using intersection():', A.intersection(B))

The difference between two sets A and B include elements of set A that are not present on set B.
print('Difference using &:', A - B)
print('Difference using difference():', A.difference(B))

The symmetric difference between two sets A and B includes all elements of A and B without the
common elements.
print('Symmetric Difference using ^:', A ^ B)
print('Symmetric Difference using symmetric_difference():',
A.symmetric_difference(B))
A, B = {1, 3, 5}, {5, 3, 1}
if A == B:
Check if two sets are print('Set A and Set B are equal')
equal else:
print('Set A and Set B are not equal')
85
Python Set
Python Set methods
Method Description Method Description
add() Adds an element to the set Returns True if another set
issubset()
Removes all elements from contains this set
clear()
the set Returns True if this set
issuperset()
copy() Returns a copy of the set contains another set
Returns the difference of two Removes and returns an
difference() pop() arbitrary set element. Raises
or more sets as a new set
KeyError if the set is empty
Removes all elements of
difference_update() Removes an element from the
another set from this set
remove() set. If the element is not a
Removes an element from member, raises a KeyError
the set if it is a member. (Do
discard() Returns the symmetric
nothing if the element is not
in set) symmetric_difference() difference of two sets as a
new set
Returns the intersection of
intersection() Updates a set with the
two sets as a new set symmetric_difference_update(
symmetric difference of itself
Updates the set with the )
and another
intersection_update() intersection of itself and
another Returns the union of sets in a
union()
new set
Returns True if two sets have
Isdisjoint() Updates the set with the
a null intersection update()
union of itself and others

86
Python Set
Exercises
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.

87
Python Collections
Python Dictionary

88
Python Dictionary
Introduction
▸ A Python dictionary is a data structure that stores the value in key:value pairs.

dict_var = { key1: value1’, key2: ‘value2’, ...}


▸ Python dictionaries are ordered and can not contain duplicate keys.
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
# printing the dictionary
print(country_capitals)
# {'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

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

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

90
Python Dictionary
Nested Dictionaries
▸ 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.
Accessing nested dictionary items
company_org_chart = {
"Marketing": { print(company_org_chart["Sales"]["ID122"]) # -->David Lee
"ID234": "Jane Smith" print(company_org_chart["Engineering"]["ID321"]) # -->Maryam Sam
},
"Sales": {
"ID123": "Bob Johnson",
"ID122": "David Lee"
},
"Engineering": {
"ID303": "Radhika Potlapally",
"ID321": "Maryam Samimi"
}
}

91
Python Dictionary
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.

92
Python Dictionary
Exercises
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.

93
Python Dictionary
Exercises
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. # Resulting dictionary:
dept_employees = {
"Engineering": {
# Input: 1001: {"name": "Alice", "salary":
employees = { 75000},
1001: {"name": "Alice", "department": 1003: {"name": "Charlie",
"Engineering", "salary": 75000}, "salary": 80000}
1002: {"name": "Bob", "department": },
"Sales", "salary": 50000}, "Sales": {
1003: {"name": "Charlie", "department": 1002: {"name": "Bob", "salary":
"Engineering", "salary": 80000}, 50000},
1004: {"name": "Dave", "department": 1005: {"name": "Eve", "salary":
"Marketing", "salary": 60000}, 55000}
1005: {"name": "Eve", "department": },
"Sales", "salary": 55000} "Marketing": {
} 1004: {"name": "Dave", "salary":
60000}
}
}
94
Summary

96
Thanks for your listening!

97

You might also like