Python
Fundamentals
Friday, August 9, 2024 1
Agenda
• Recap
• Lists, Tuples, Dictionaries, Sets
• Conditions
• Checking for Equality
• Ignoring Case When Checking for Equality
• Checking for Inequality
• Numerical Comparisons
• Checking Multiple Conditions
• Checking Whether a Value is in a List or Not
• Boolean Expressions
• If Statements
• The if-elif-else Chain
• Using if with Lists
• Checking that a list is Not Empty
2
Agenda
• Loops
• Basic “for” Loop
• “for” Loop with range ()
• Iterating Through a Dictionary
• Basic “while” Loop
• “while” loop with Lists & Dicationary
• Functions
• Defining and Calling Function
• Function with Parameters
• Function with Multiple Parameters
• Default Parameter Values
• Keyword Arguments
3
Sets
● Syntax: Set_variable = {“a”, “b”, 6-}
● You can apply len(), type().
● It can contain different data types.
● You can use set() constructor instead of the curly brackets.
● You cannot access them the same way of indexing.
● You cannot modify an item using basic assignment: set_variable[0]
=‘c’
4
Sets Notes & Methods
● Accessing Set elements use: IN operator.
● You can add items using add()
● Same as extend() in lists you can use update() to add two sets/any other
sequence
● Remove(): to remove and item from the set
● Union() == Update() but union() returns a new set. Update() modifies.
● Intersection(): get the duplicated items from two sets and return a new set.
● intersection_update() same as intersection() but updates directly.
5
Dictionaries
● Syntax: Dict_variable = {“name”: “Merna”, “age”: 20, 1: [1,2,3]}
● You can apply len(), type().
● It can contain different data types.
● You can use dict() constructor instead of the curly brackets.
● You can access them using Keys.
● You can modify an item using basic assignment: dict_variable[‘name’]=
‘Ahmed’
6
DICTIONARY Notes & Methods
● Dictionaries can be deleted using the del function in python.
● Duplicate keys are not allowed. Last key will be assigned while others are Some
ignored. important built-in functions:
● .clear() to clear all elements of the dictionary.
● .copy() to copy all elements of the dictionary to another variable.
● .fromkeys() to create another dictionary with the same keys.
● .get(key) to get the values corresponding to the passed key.
● .has_key() to return True if this key is in the dictionary.
● .items() to return a list of dictionary (key, value) tuple pairs.
● .keys() to return list of dictionary dictionary keys.
● .values() to return list of dictionary dictionary values.
● .update(dict) to add key-value pairs to an existing dictionary.
7
Comparison between the list, Tuple, Set,
Dictionary :
8
Comparison between the list, Tuple, Set,
Dictionary :
• Ordered means that each element won’t change its place until you modify it.
• Changeable means you can edit its element.
• No Duplicates means that it only contains unique values.
• Indexed means you can access each element by its index/position except dictionaries you
access elements using keys.
9
Conditional Statement
10
Syntax
Syntax Structure:
if condition:
•Indented block of code to execute if the condition is true.
elif condition:
•Indented block of code to execute if the elif condition is true.
else:
•Indented block of code to execute if none of the above conditions are true.
11
Syntax
• Nested conditionals are conditional statements within other
conditional statements. This allows you to create more complex
decision-making structures.
if condition1:
# code block
if condition2:
# nested code block
elif condition3:
# nested code block
else:
# nested code block
else:
# code block
12
Checking Pass/Fail Status
13
Conditions
Checking for Equality
car = “bmw" car = “audi"
Is True car == “bmw" Is False
car == “bmw"
Ignoring Case When Checking for Equality
car = "Audi" car = "Audi"
car == "audi" Is False car.lower() == "audi Is True
14
Conditions
Checking for Inequality
requested_topping = "mushrooms"
if requested_topping != "anchovies"
print("Hold the anchovies!")
Numerical Comparisons
age = 18 answer = 17
age == 18 Is True if answer != 42:
print("That is not the correct answer")
15
Conditions
Checking Multiple Conditions
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21 Is False
age_1 = 22
age_0 >= 21 and age_1 >= 21 Is True
16
Conditions
Checking Whether a Value is in a List
requested_toppings = ['mushrooms', 'onions', 'pineapple’]
‘mushrooms’ in requested_toppings Is True
‘pepproni’ in requested_toppings Is False
Checking Whether a Value is Not in a List
banned_users = ['andrew', 'carolina','david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")
17
Conditions
Boolean Expressions
game_active = True
can_edit = False
18
Conditions
If Statements
age = 19
if age >= 18:
print("you are old enough to vote!")
If-else Statements
age = 17
if age >= 18:
print("you are old enough to vote!")
print ("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print ("Please register to vote as soon as you turn 18!")
19
Conditions
The if-elif-else Chain
age = 12
if age < 4:
print("your are addmission cost is 0$.")
elif age < 18:
print("your admission cost is 25$.")
else:
print("your admission cost is 40$.")
20
Let’s Practice
21
Practice
• Question 1:
• Write a program that takes three integers, and prints out the smallest number.
Ans 1:
22
Practice
• Question 2:
• Write a program that reads a student grade percentage and prints "Excellent" if his grade is greater than or
equal 85, "Very Good" for 75 or greater; "Good" for 65, "Pass" for 50, "Fail" for less than 50.
Ans 2:
23
Loops
24
Loops
Definition:
• Loops allow you to execute a block of code repeatedly.
• Two main types of loops in Python: for loops and while loops.
Syntax Structure:
for variable in iterable: while condition:
# code block # code block
25
Loops: “for” Loop
Basic “for” Loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
“for” Loop with range ()
for i in range(5):
print(f"Iteration {i}")
Iterating Through a Dictionary
student = {"name": "Alice", "age": 22, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
26
Loops: “while” Loop
Basic “while” Loop
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
if message != 'quit':
print(message)
27
Loops: “while” Loop
“while” Loop with Lists & Dictionary
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
if message != 'quit':
print(message)
28
Loops: “while” Loop
“while” Loop with Dictionary
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary.
responses[name] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
29
Let’s Practice
30
Practice
• Question 1:
• Print sum of first 100 integers.
Ans 1:
31
Practice
• Question 2:
• Write a program that given a number N. Print all even numbers between 1 and N inclusive in separate lines.
Ans 2:
32
Functions
33
Function
Definition:
• A function is a reusable block of code that performs a specific task.
• Functions help organize code into manageable sections and avoid
repetition.
Components:
• Function Definition: Specifies the function's name, parameters, and the
code block to be executed.
• Function Call: Executes the function and passes any required arguments.
• Return Value: The value a function provides after it completes execution.
34
Functions
Defining and Calling Function
def greet():
print("Hello, world!")
# Calling the function
greet()
Function with Parameters
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
# Calling the function with an argument
greet_person("Alice")
35
Functions
Function with Multiple Parameters
# Function with multiple parameters
def add(a, b):
return a + b
# Calling the function with arguments
result = add(3, 5)
print(result)
Default Parameter Values
# Function with default parameter values
def greet(name="Guest"):
print(f"Hello, {name}!")
# Calling the function without an argument
greet()
# Calling the function with an argument
greet("Bob")
36
Functions
Keyword Argument
# Function with keyword arguments
def describe_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}.")
# Calling the function with keyword arguments
describe_person(name="Alice", age=30, city="New York")
37
Let’s Practice
38
Practice
• Question 1:
• Write a function that reads the radius of a circle and calculates the area and circumference then prints the
results.
Ans 1:
39
Practice
• Question 2:
Ans 2:
40
Summary Question
• Summary Question:
• Write a function that takes one integer and print if it is prime or not.
Ans:
41
Any Questions ?
42
Thank You ♥♥
43