Python Data Science Fundamentals Guide
Python Data Science Fundamentals Guide
Lecturer information
▸Full name: Võ Văn Hải
▸Email: vovanhai@[Link]
▸Zalo: UEH_Python_25D1INF50915201_S7
vovanhai@[Link] 2
1
1/5/2026
Ask
The art and science of asking questions is the source of all knowledge.
- Thomas Berger
vovanhai@[Link] 3
Failure
▸Coding is all about trial and error.
▸Don't be afraid of it.
▸Error messages aren't scary, they are useful.
vovanhai@[Link] 4
2
1/5/2026
Introduction to
3
1/5/2026
History
▸Started by Guido Van Rossum as a hobby
▸Now widely spread
▸Open Source! Free!
▸Versatile
Source: [Link]
vovanhai@[Link] 7
Source: [Link]
vovanhai@[Link] 8
4
1/5/2026
vovanhai@[Link] 9
vovanhai@[Link] 11
11
5
1/5/2026
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!")
vovanhai@[Link] 12
12
Variables
Python as a calculator
▸Let us calculate the distance between Edinburgh and London in km
The variable mileToKm can be used in the next block without having to define it again
vovanhai@[Link] 13
13
6
1/5/2026
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))
vovanhai@[Link] 15
15
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:
vovanhai@[Link] 16
16
7
1/5/2026
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"
▸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
vovanhai@[Link] 18
18
8
1/5/2026
▸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 i, f, h = 10, 13.6, 365
- %s – string print("i=%d, f=%f, h=%x " % (i, f, h))
# i=10, f=13.600000, h=16d
- %x –hexadecimal
- %o – octal
vovanhai@[Link] 19
19
vovanhai@[Link] 20
20
9
1/5/2026
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
vovanhai@[Link] 21
21
22
22
10
1/5/2026
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'>
vovanhai@[Link] 23
23
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
vovanhai@[Link] 24
24
11
1/5/2026
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
vovanhai@[Link] 25
25
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 'float'> x = 3 + 5j # <class 'complex'>
y = 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 complex: print([Link](1, 10))
# convert from int to float: c = complex(x)
a = float(x)
vovanhai@[Link] 26
26
12
1/5/2026
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 1
x = int(1) # x will be 1 y = int(2.8) # y will be 2
y = float(2.8) # y will be 2.8
y = int(2.8) # y will be 2 z = int("3") # z will be 3
z = float("3") # z will be 3.0
z = int("3") # z will be 3
w = float("4.2") # w will be 4.2
vovanhai@[Link] 27
27
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.
vovanhai@[Link] 28
28
13
1/5/2026
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: print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
▸You can assign a multiline string to a variable by using three quotes:
a = """Lorem ipsum dolor sit amet, a = '''Lorem ipsum dolor sit amet,
ut labore et dolore magna aliqua.""" ut labore et dolore magna aliqua.'''
29
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
vovanhai@[Link] 30
30
14
1/5/2026
Strings
Modify Strings
▸The upper() and lower() methods return the string in upper case and lower case:
a = "Hello, World!"
print([Link]())
print([Link]())
▸The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
▸The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("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([Link](",")) # returns ['Hello', ' World!']
vovanhai@[Link] 31
31
Strings
String Format
▸we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
- Or, using with an expression # Return "Expensive" if the price is over 50, otherwise return "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
vovanhai@[Link] 32
32
15
1/5/2026
Strings
String Format (continue)
price = 59000
▸Formatting types txt = f"The price is {price:,} dollars" # -> The price is 59,000 dollars
vovanhai@[Link] 33
33
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([Link](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([Link](age, name)) # His name is John. John is 36 years old.
vovanhai@[Link] 34
34
16
1/5/2026
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
vovanhai@[Link] 35
35
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.
vovanhai@[Link] 36
36
17
1/5/2026
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({})
vovanhai@[Link] 37
37
Operators
38
38
18
1/5/2026
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
vovanhai@[Link] 39
39
40
19
1/5/2026
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
vovanhai@[Link] 41
41
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
vovanhai@[Link] 42
42
20
1/5/2026
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.
1
5. Calculate the slope, x-intercept and y-intercept of y = 2x -2 𝑦= 𝑥+1
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.
vovanhai@[Link] 43
43
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. _
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
vovanhai@[Link] 44
44
21
1/5/2026
45
45
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 Conditional Flow in Python
- Python If Statement
- Python If Else Statement
- Python Nested If Statement
- Python Elif
- Ternary Statement (Shorthand If Else Statement)
vovanhai@[Link] 46
46
22
1/5/2026
vovanhai@[Link] 47
47
vovanhai@[Link] 48
48
23
1/5/2026
vovanhai@[Link] 49
49
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')
vovanhai@[Link] 50
50
24
1/5/2026
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")
vovanhai@[Link] 51
51
vovanhai@[Link] 52
52
25
1/5/2026
53
53
▸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 for var in sequence: The for loop iterates over the elements
of sequence in order. In each iteration, the
# statements
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)
vovanhai@[Link] 54
54
26
1/5/2026
▸Note: The else block will not execute if the for loop is stopped by a break
statement.
vovanhai@[Link] 55
55
vovanhai@[Link] 56
56
27
1/5/2026
57
vovanhai@[Link] 58
58
28
1/5/2026
59
59
▸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('The end.')
vovanhai@[Link] 60
60
29
1/5/2026
vovanhai@[Link] 61
61
62
30
1/5/2026
vovanhai@[Link] 63
63
31