Control statements regulate the flow of execution in a Python program. They determine how and when certain blocks of code execute.
๐น Types of Control Statements in Python
Python has three main types of control statements:
- Conditional Statements (if, if-else, if-elif-else) โ Decision making
- Looping Statements (for, while) โ Repetition
- Jump Statements (break, continue, pass) โ Control flow modification
1๏ธโฃ Conditional Statements (Decision Making)
Conditional statements allow Python to execute a block of code only if a condition is met.
โ if Statement
Executes a block only if the condition is True.
age = 20
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
โ if-else Statement
Executes one block if the condition is True, otherwise executes another block.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
Output:
You cannot vote.
โ if-elif-else Statement
Used when there are multiple conditions to check.
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
2๏ธโฃ Looping Statements (Iteration)
Loops are used to execute a block of code multiple times.
โ for Loop (Definite Iteration)
Loops over an iterable (like a list, string, or range).
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
โ while Loop (Indefinite Iteration)
Executes a block as long as a condition is True.
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
3๏ธโฃ Jump Statements (Control Flow Modification)
Jump statements allow modification of normal flow inside loops.
โ break Statement
Stops the loop immediately.
for i in range(1, 6):
if i == 3:
break # Stops the loop at 3
print(i)
Output:
1
2
โ continue Statement
Skips the current iteration and continues to the next.
for i in range(1, 6):
if i == 3:
continue # Skips 3
print(i)
Output:
1
2
4
5
โ pass Statement
A placeholder statement that does nothing (useful for defining empty functions or loops).
for i in range(5):
pass # Does nothing but avoids an error
๐น Summary Table of Control Statements
Statement | Purpose |
---|---|
if |
Executes code if the condition is True |
if-else |
Executes one block if True, another if False |
if-elif-else |
Checks multiple conditions |
for loop |
Iterates over a sequence |
while loop |
Loops while a condition is True |
break |
Stops the loop immediately |
continue |
Skips the current iteration |
pass |
Does nothing, acts as a placeholder |
Would you like real-world examples using these concepts? ๐
Leave a Reply