Python
Lecure 3
By Japhet Moise H.
Control Structures in Python
• Introduction
• Control structures are fundamental programming
constructs that allow for more dynamic execution paths
based on conditions or by iterating over collections of
data.
• Control structures including conditional statements,
loops, and branching mechanisms that Python uses to
execute code conditionally, repeatedly, or iteratively.
1. Conditional Statements (if, elif, else)
• Purpose: Execute different blocks of code based on certain
conditions.
• Syntax:
if condition:
# code to execute if condition is true
elif another_condition:
# code to execute if the
another_condition is true
else:
# code to execute if none of the above
conditions are true
Example
age = int(input(“enter age”))
if age >= 18:
print("You are an adult.")
elif age < 18 and age > 0:
print("You are a minor.")
else:
print("Invalid age.")
question • Write python program which
simulate USSD of banking
system where system has the
following menu:
1. PIN Verification
2. Check Balance
3. Withdraw Money
4. Deposit Money
5. Exit
Loops in Python
• Loops or Iteration Statements in Programming are helpful
when we need a specific task in repetition. They’re
essential as they reduce hours of work to seconds
• In Python, loops are used to execute a block of code
repeatedly until a certain condition is met. The two main
types of loops in Python are the for loop and the while
loop
For Loop
• The for loop in Python is used to iterate over a sequence (like a
list, tuple, dictionary, set, or string)
• syntax:
for element in sequence:
# do something with element
fruits =
• Example:
["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
• The while loop executes as long as the condition (usually
involving one or more variables) is true:
• Syntax:
while condition:
# do something
• Example: count = 0
while count < 3:
print("Looping")
count += 1
Loop Control Statements
Python provides control statements
like break, continue, and pass to modify the
behavior of loops
• break: Exits the loop.
• continue: Skips to the next iteration.
• pass: Does nothing; acts as a placeholder.
Loop Control Statements
Example using break:
for i in range(5):
if i == 3:
break
print(i)
Example using continue:
for i in range(5):
if i == 3:
continue
print(i)
Example using pass:
for i in range(5):
pass # This will do nothing but is syntactically
valid
Thank you!!!