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
of control structures are:
1. Conditional Statements (Decision Making)
2. Looping Statements (Iteration)
3. Branching (Break, Continue, Pass)
1. Conditional Statements
Conditional statements are used to perform different actions based on different conditions. Python uses if,
elif, and else for decision-making.
Syntax:
if condition:
# code block
elif another_condition:
# another code block
else:
# fallback code block
Example:
age = 20
if age < 18:
Control Structures in Python
print("You are a minor.")
elif age == 18:
print("You just became an adult.")
else:
print("You are an adult.")
2. Looping Statements
Loops are used to repeat a block of code multiple times.
A. for Loop
Used to iterate over a sequence (like a list, tuple, dictionary, or string).
Syntax:
for variable in sequence:
# code block
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
B. while Loop
Used to execute a block of code as long as a condition is true.
Control Structures in Python
Syntax:
while condition:
# code block
Example:
count = 1
while count <= 5:
print(count)
count += 1
3. Branching Statements
These are used to change the flow inside loops or functions.
A. break
Used to exit a loop prematurely.
Example:
for num in range(10):
if num == 5:
break
print(num)
Output: 0 1 2 3 4
Control Structures in Python
B. continue
Skips the current iteration and goes to the next one.
Example:
for num in range(5):
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:
pass # do nothing for now
Nesting Control Structures
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.