Fundamentals 7 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Master Python Control Flow: If/Else, For, While & Practical Tips

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 fail

Example: grade classification

score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("D")
# Output: B

Tips:

Indentation must be consistent (recommended 4 spaces)
Use and / or to combine multiple conditions
not for negation

3. for loop – the tool for traversing data structures

Basic syntax:

for 变量 in 可迭代对象:
    # loop body

Example 1: iterate a list

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
# Output:
# apple
# banana
# cherry

Example 2: use range() to print numbers

for i in range(1, 6):  # excludes 6
    print(i)
# Output: 1 2 3 4 5

Example 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: Beijing

Tips:

range() supports start, stop, step
break can exit loop early
continue skips current iteration

4. while loop – repeat while a condition holds

Basic syntax:

while 条件:
    # repeated execution while condition is true

Example: 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 numbers

6. 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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Code Examplesprogramming fundamentalsif-elseControl Flowfor loopwhile-loop
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.