What You'll Learn in This Blog:
if
, elif
, else
statementsfor
and while
loopsbreak
, continue
, pass
statementsControl flow refers to the order in which your code is executed. By default, Python runs code line by line from top to bottom. Control flow allows you to make decisions, repeat tasks, and react to data, making your programs dynamic.
if
, elif
, else
if
Statement
age = 18
if age >= 19:
print("You are eligible to vote.")
If the condition evaluates to True
, the block inside the if
runs.
if
...else
Statement
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("Sorry, you must be at least 18.")
Executes the else
block if the conditions is False
.
if
...elif
...else
Chain
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C or lower")
checks multiple conditions in sequence.
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater or equal | a >= b |
<= | Less or equal | a <= b |
Operator | Description | Example |
---|---|---|
and | All conditions must be True | a > 5 and b < 10 |
or | At least one must be True | a > 5 or b < 10 |
not | Reverses condition result | not a == b |
for
LoopUsed to iterate over sequence (lists, strings, ranges, etc.)
for i in range(5):
print(i)
Output: 0 1 2 3 4
while
LoopRepeats a block of code as long as a condition is True
.
i = 0
while i < 5:
print(i)
i += 1
Same Output: 0 1 2 3 4
Statement | Purpose | Example Usage |
---|---|---|
break | Exit the loop early | Stop loop when a condition is met |
continue | Skip the current iteration | Skip even numbers in a loop |
pass | Placeholder for future code | Used where code is syntactically required but not yet implemented |
Examples:
# break example
for i in range(10):
if i == 5:
break
print(i) # Prints 0 to 4
# continue exmaple
for i in range(5):
if i == 2:
continue
print(i) # Skips printing 2
# pass example
for i in range(3):
pass # Does nothing, placeholder
Example: Nested if
inside a for
loop
for num in range(1, 6):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
🔸 Problem: Ask the user to enter a number and check the following:
Example:
# Sample Output:
# Enter a number: 15
# Divisible by both 3 and 5
# The number is odd
# Even numbers: 0 2 4 6 8 10 12 14
Practice Tasks
Topic | Example |
---|---|
if , else | if x > 0: print("Positive") |
elif | elif x == 0: print("Zero") |
Loops | for i in range(5): |
break / continue | break to stop loop, continue to skip |
Comparison | x >= y |
Logical | x > 0 and y < 10 |
Leave a Reply