Control Structures in Python
Control Structures in Python
Control structures are the fundamental building blocks that control the flow of a program. They help
programmers make decisions, repeat tasks, or choose between alternatives. In Python, the three main types
1. Conditional Statements
Conditional statements are used to perform different actions based on different conditions. Python uses if,
Syntax:
if condition:
# code block
elif another_condition:
else:
Example:
age = 20
else:
2. Looping Statements
A. for Loop
Syntax:
# code block
Example:
print(fruit)
B. while Loop
Syntax:
while condition:
# code block
Example:
count = 1
print(count)
count += 1
3. Branching Statements
A. break
Example:
if num == 5:
break
print(num)
Output: 0 1 2 3 4
Control Structures in Python
B. continue
Example:
if num == 2:
continue
print(num)
Output: 0 1 3 4
C. pass
Used as a placeholder. It does nothing but avoids errors from empty blocks.
Example:
if True:
You can also nest control structures, i.e., use if inside for, while inside if, etc.
Example:
for i in range(3):
if i == 1:
Control Structures in Python
print("Middle number")
else:
print("Number:", i)
Output:
Number: 0
Middle number
Number: 2
Conclusion
Control structures are essential for writing logical and efficient Python programs. They allow the program to
make decisions, repeat actions, and respond dynamically to data. By understanding how if, for, while, break,
and other control statements work, you can write more flexible and powerful code.