Control Flow
Conditionals and Loops
Introduction
Control flow is the backbone of any programming language, allowing you to make decisions and repeat tasks based on specific conditions. In this post, we’ll explore Python’s conditionals (if
, else
, elif
) and loops (for
, while
), along with key keywords like break
and continue
.
1. Conditionals: Making Decisions
Conditionals allow your program to execute specific blocks of code depending on the value of a condition (a Boolean expression).
Basic Syntax
python
Copy codeif condition:
# Code to execute if condition is True
elif another_condition:
# Code to execute if the first condition is False and this one is True
else:
# Code to execute if all conditions are False
Examples
python
Copy code= 20
age
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")
2. Logical Operators
Conditionals often use logical operators to combine or modify conditions:
and
: True if both conditions are True.or
: True if at least one condition is True.not
: Reverses the condition.
Example:
python
Copy code= 10
x = 20
y
if x > 5 and y > 15:
print("Both conditions are True.")
if not x < 5:
print("x is not less than 5.")
3. Loops: Repeating Tasks
The for
Loop
The for
loop iterates over a sequence (like a list, string, or range).
Example 1: Iterating Over a List
python
Copy code= ["apple", "banana", "cherry"]
fruits
for fruit in fruits:
print(fruit)
Example 2: Using range
python
Copy codefor i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
The while
Loop
The while
loop continues executing as long as the condition is True
.
Example:
python
Copy code= 0
count
while count < 5:
print(count)
+= 1 # Increment count count
4. Controlling Loops
The break
Statement
Exits the loop immediately.
Example:
python
Copy codefor i in range(10):
if i == 5:
break # Exit the loop
print(i)
The continue
Statement
Skips the current iteration and moves to the next.
Example:
python
Copy codefor i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
5. Nested Conditionals and Loops
You can nest conditionals inside loops and vice versa to handle more complex scenarios.
Example:
python
Copy codefor i in range(1, 6):
if i % 2 == 0:
print(f"{i} is even.")
else:
print(f"{i} is odd.")
6. Infinite Loops
Be cautious when writing loops. Forgetting to update the condition can lead to infinite loops.
Example of an Infinite Loop (Avoid This!)
python
Copy codewhile True:
print("This will run forever!")
To stop such a loop, you can press Ctrl+C
in your terminal.
Conclusion
With conditionals and loops, you can control the flow of your Python programs effectively. These tools enable you to build flexible and powerful logic.