Control Statements in Python
Control statements are used to control the flow of execution in a program.
Python provides various conditional and looping statements to make
decisions and repeat tasks.
1. if Statement
The if statement is used to test a condition. If the condition is true, the
block of code under if is executed.
Syntax:
if condition:
# block of code
Example:
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
2. if...else Statement
The if...else statement provides two paths: one executed when the
condition is true, and another when it is false.
Syntax:
if condition:
# block executed if condition is true
else:
# block executed if condition is false
Example:
age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Output:
Not eligible to vote
3. if...elif...else Statement
When multiple conditions need to be checked, elif (short for else if) is
used. It prevents deep nesting of if statements.
Syntax:
if condition1:
# block executed if condition1 is true
elif condition2:
# block executed if condition2 is true
elif condition3:
# block executed if condition3 is true
else:
# block executed if all conditions are false
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Output:
Grade B
4. for Loop
The for loop is used to iterate over a sequence (list, tuple, string, range,
etc.).
Syntax:
for variable in sequence:
# block of code
Example:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
5. while Loop
The while loop keeps executing a block of code as long as a condition is
true.
Syntax:
while condition:
# block of code
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
6. break Statement
The break statement is used to exit a loop immediately, regardless of the
condition.
Syntax:
for/while loop:
if condition:
break
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
7. continue Statement
The continue statement skips the current iteration of the loop and moves
to the next iteration.
Syntax:
for/while loop:
if condition:
continue
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
8. pass Statement
The pass statement is a null operation. It is used when a statement is
syntactically required but you don’t want any code to execute.
Syntax:
if condition:
pass
Example:
for i in range(5):
if i == 3:
pass # placeholder for future code
else:
print(i)
Output:
0
1
2
4
Summary
if → Executes block if condition is true.
if...else → Executes one block if true, another if false.
if...elif...else → Multiple conditions checking.
for → Iterates over a sequence.
while → Repeats while condition is true.
break → Exits loop prematurely.
continue → Skips current iteration.
pass → Placeholder, does nothing.