Python
Python
Penh
Faculty of Engineering
Introduction to
Python
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
Getting Started
Setup environment
• Download and Install python from https://www.python.org/downloads/ based on the
operating system.
• Check if python installed and which version:
python --version #type in terminal or command prompt
• Use python virtual environments to isolate versions of Python and its dependencies
python -m venv env #Create virtual environment with folder ‘env’
• Activate python virtual environment
source env/bin/activate #for Mac OS or other Linux distributions
env\scripts\activate #for Windows
Getting Started
Create and run a Python Script
• We can write a program in any text editor, save it in .py format and then run via a Command
Line
• Example:
• Write python code in text file
print(“Hello world!”)
• Save the file with extension “.py” i.e. test.py
• Run the python script
python test.py # will see the output “Hello World!”
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
Data Type
Data Type
Data Type
Variables
A variable is a label that you can assign a value to it. The value of a variable
can change throughout the program.
For example:
counter = 1
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
Comparison Operators
Python has six comparison operators, which are as follows:
• Less than ( < )
• Less than or equal to (<=)
• Greater than (>)
• Greater than or equal to (>=)
• Equal to ( == )
• Not equal to ( != )
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
If Statement
• Use the if statement when you want to run a code block based on a
condition.
• Use the if...else statement when you want to run another code block if the
condition is not True.
• Use the if...elif...else statement when you want to check multiple conditions
and run the corresponding code block that follows the condition that
evaluates to True.
If Statement
If statement
• The syntax of the if statement is as follows:
if condition:
if-block
• For example:
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")
If Statement
If…else statement
• The following shows the syntax of the if...else statement:
if condition:
if-block;
else:
else-block;
If Statement
If…else statement
• For example:
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")
If Statement
If…elif…else statement
• The following shows the syntax of the if...elif…else statement:
if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-block
If Statement
If…elif…else statement
• For example:
age = input('Enter your age:')
• For example:
for index in range(5):
print(index)
for loop with range()
Specifying the increment for the sequence
• To increase the start value by a different number, you use the following form of
the range() function:
• For example:
for index in range(0, 11, 2):
print(index)
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
Functions
• A Python function is a reusable named block of code that performs a task or returns a
value.
def greet():
""" Display a greeting to users """
print('Hi’)
• Calling a function:
greet()
• Output:
Functions
Passing information to Python functions
• When you add a parameter to the function definition, you can use it as a variable inside the
function body:
def greet(name):
print(f"Hi {name}")
• Calling a function:
greet('John’)
• Output:
Functions
Python functions with multiple parameters
The following example defines a function called sum() that calculates the sum of two numbers:
def sum(a, b):
return a + b
total = sum(10,20)
print(total)
Output:
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
List
• A list is an ordered collection of items.
• Use square bracket notation [] to access a list element by its index. The first element has an
index 0.
• Use a negative index to access a list element from the end of a list. The last element has an
index -1.
• Use list[index] = new_value to modify an element from a list.
• Use append() to add a new element to the end of a list.
• Use insert() to add a new element at a position in a list.
• Use remove() to remove an element from a list.
List
• Python uses the square brackets ([]) to indicate a list. The following shows an empty list:
empty_list = []
• The following shows how to define a list of strings:
colors = ['red', 'green', 'blue']
print(colors)
Output:
• A list can contains other lists. The following example defines a list of lists:
coordinates = [[0, 0], [100, 100], [200, 200]]
print(coordinates)
Output:
List
Accessing elements in a list
• For example, the following shows how to access the second element of the numbers list:
numbers = [1, 3, 2, 7, 9, 4]
print(numbers[1])
Output:
• The negative index allows you to access elements starting from the end of the list.
numbers = [1, 3, 2, 7, 9, 4]
print(numbers[-1])
print(numbers[-2])
Output:
List
Modifying elements in a list
numbers = [1, 3, 2, 7, 9, 4]
numbers[0] = 10
print(numbers)
Output:
List
Adding elements to the list
• The append() method appends an element to the end of a list. For example:
numbers = [1, 3, 2, 7, 9, 4]
numbers.append(100)
print(numbers)
Output:
• The insert() method adds a new element at any position in the list.
numbers = [1, 3, 2, 7, 9, 4]
numbers.insert(2, 100)
print(numbers)
Output:
List
Removing elements from a list
• The del statement allows you to remove an element from a list by specifying the position of the element.
numbers = [1, 3, 2, 7, 9, 4]
del numbers[0]
print(numbers)
Output:
numbers.remove(9)
print(numbers)
Output:
Tuples
• Tuples are immutable lists. Use tuples when you want to define a list that cannot change.
• The following example defines a tuple called rgb:
rgb = ('red', 'green', 'blue')
print(rgb[0])
print(rgb[1])
print(rgb[2])
Output:
List Comprehensions
• The straightforward way is to use a for loop:
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number**2)
print(squares)
• The following shows how to use list comprehension to make a list of squares from
the numbers list:
numbers = [1, 2, 3, 4, 5]
squares = [number**2 for number in numbers]
print(squares)
Content
1. Getting Started
2. Variables
3. Comparison Operators
4. Control flow
5. Functions
6. Lists
7. Dictionaries
Dictionaries
• A Python dictionary is a collection of key-value pairs where each key is associated with a value.
• The following example defines a dictionary with some key-value pairs:
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
Dictionaries
Accessing values in a Dictionary
• Using square bracket notation
print(person['first_name'])
print(person['last_name'])
Output:
ssn = person.get('first_name')
Dictionaries
Adding new key-value pairs
• The following example adds a new key-value pair to the person dictionary:
person['gender'] = 'Famale'
person['age'] = 26
print(person)
Output:
{'first_name': 'John', 'last_name': 'Doe', 'age': 26, 'favorite_colors': ['blue', 'green'], 'active': True}
Dictionaries
Removing key-value pairs
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
del person['active']
print(person)
Output:
{'first_name': 'John', 'last_name': 'Doe', 'age': 25, 'favorite_colors': ['blue', 'green']}
Dictionaries Comprehension
Using Python dictionary comprehension to transform a dictionary
To increase the price of each stock by 2%, you may come up with a for loop like this:
stocks = {
'AAPL': 121,
'AMZN': 3380,
'MSFT': 219,
'BIIB': 280,
'QDEL': 266,
'LVGO': 144
}
new_stocks = {}
for symbol, price in stocks.items():
new_stocks[symbol] = price*1.02
print(new_stocks)
Dictionaries Comprehension
Using Python dictionary comprehension to transform a dictionary (Continue)
• The following example shows how to use dictionary comprehension to achieve the same result:
stocks = {
'AAPL': 121,
'AMZN': 3380,
'MSFT': 219,
'BIIB': 280,
'QDEL': 266,
'LVGO': 144
}
print(new_stocks)
Thank You!