Master Python Control Flow: If, For, While Explained with Real Examples
This guide walks beginners through Python's control flow structures—if statements, for loops, and while loops—explaining their syntax, demonstrating multiple conditional checks, iteration over sequences, and combined usage with clear code examples that illustrate filtering, accumulation, and prime number detection.
If Statement
The if statement lets you execute a block of code only when a specific condition is true. An optional else clause handles the opposite case.
# if statement executes a block when the condition is met.
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")Multiple conditions can be chained with elif to cover several ranges.
# multiple condition checks
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")For Loop
The for loop iterates over each element in a sequence such as a list, tuple, or string.
# iterate over a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)It can also iterate over a string character by character.
# iterate over a string
for letter in "hello":
print(letter)While Loop
The while loop repeats as long as a condition remains true. It is useful for situations where the number of iterations isn’t known in advance.
# while loop runs while the condition is true
count = 0
while count < 5:
print(count)
count += 1A common pattern is an infinite loop with a break condition.
# break out of an infinite loop
number = 1
while True:
print(number)
number += 1
if number > 10:
breakCombined Use Cases
By nesting if statements inside loops, you can create more sophisticated logic.
# filter even numbers
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(num)Accumulate values until a target is reached using a while loop.
# accumulate until total reaches 100
total = 0
num = 1
while total < 100:
total += num
num += 1
print(total)Combine functions, loops, and conditionals to solve algorithmic problems, such as finding the first prime number.
# find the first prime number
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
number = 2
while True:
if is_prime(number):
print(f"The first prime number is {number}")
break
number += 1Understanding these control‑flow constructs is essential for building flexible and intelligent Python programs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
