Master Python Control Flow: If/Else, For, While & Practical Tips
This article introduces Python control flow, explaining conditional statements (if, elif, else) and loop constructs (for, while) with clear syntax, practical examples, tips, and exercises to help readers master decision‑making and iteration in their programs.
In programming, control flow determines the order in which statements are executed. Mastering if/else branching, for and while loops is essential for building complex logic and automation in Python.
1. What is control flow?
Control Flow refers to the path that the program follows during execution. Common Python control flow statements include:
Conditional statements: if, elif, else
Loop statements:
These statements let your program react differently based on inputs or state.
2. if / else conditional judgment – making the program “think”
Basic syntax:
if 条件:
# executed when condition is true
elif 其他条件:
# optional, multiple elif
else:
# executed when all conditions failExample: grade classification
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
# Output: BTips:
Indentation must be consistent (recommended 4 spaces)
Use and / or to combine multiple conditions
not for negation3. for loop – the tool for traversing data structures
Basic syntax:
for 变量 in 可迭代对象:
# loop bodyExample 1: iterate a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherryExample 2: use range() to print numbers
for i in range(1, 6): # excludes 6
print(i)
# Output: 1 2 3 4 5Example 3: iterate a dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# city: BeijingTips:
range() supports start, stop, step
break can exit loop early
continue skips current iteration4. while loop – repeat while a condition holds
Basic syntax:
while 条件:
# repeated execution while condition is trueExample: number guessing game
import random
number_to_guess = random.randint(1, 100)
guess = None
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 100: "))
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
print("Congratulations, you guessed it!")Be careful to avoid infinite loops; ensure the condition eventually becomes false. Use break or continue to control flow.
5. Difference between break, continue, pass
Example: skip even numbers
for i in range(1, 11):
if i % 2 == 0:
continue
print(i) # prints odd numbers6. Practice exercises
Exercise 1: Find the maximum value in a list
numbers = [10, 23, 5, 45, 30]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print("Maximum value is:", max_num)Exercise 2: Count occurrences of each letter in a string
text = "hello world"
char_count = {}
for char in text:
if char.isalpha():
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)7. Advanced tips
ternary expression to simplify if‑else
result = "Pass" if score >= 60 else "Fail"
# equivalent to:
if score >= 60:
result = "Pass"
else:
result = "Fail"Nested loops (outer + inner)
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print()
# Output:
# (1, 1) (1, 2) (1, 3)
# (2, 1) (2, 2) (2, 3)
# (3, 1) (3, 2) (3, 3)8. Summary comparison table
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.
