Python_3
Python_3
Today, you'll learn how to control the flow of your Python programs using conditionals and loops.
This will allow your programs to make decisions and repeat actions based on conditions. Follow
the plan below and work through the examples and exercises.
Step 1: Conditionals
• Definition: Conditionals allow you to execute certain blocks of code only if specific
conditions are met.
• Keywords:
o if: Checks a condition and executes the block if the condition is true.
o elif: Short for “else if,” checks another condition if the previous if (or elif) was false.
o else: Executes a block of code if none of the preceding conditions are true.
temperature = 22
else:
Key Points:
• Indentation: Python uses indentation (commonly 4 spaces) to define the code blocks.
• Comparison Operators: Use operators like >, <, ==, !=, >=, and <= to compare values.
Exercise:
2. Prints:
Step 2: Loops
A. For Loops
Purpose:
print(fruit)
for i in range(5): # 0 to 4
print("Number:", i)
B. While Loops
Purpose:
count = 0
Exercise:
python
# Test conditionals
age = 20
else:
print("Iteration", num)
n=3
while n > 0:
print("n is", n)
n -= 1
exit()