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:

<code>if 条件:
    # executed when condition is true
elif 其他条件:
    # optional, multiple elif
else:
    # executed when all conditions fail
</code>

Example: grade classification

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

Tips:

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

3. for loop – the tool for traversing data structures

Basic syntax:

<code>for 变量 in 可迭代对象:
    # loop body
</code>

Example 1: iterate a list

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

Example 2: use range() to print numbers

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

Example 3: iterate a dictionary

<code>person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
for key, value in person.items():
    print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# city: Beijing
</code>

Tips:

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

4. while loop – repeat while a condition holds

Basic syntax:

<code>while 条件:
    # repeated execution while condition is true
</code>

Example: number guessing game

<code>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!")
</code>

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

<code>for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i)  # prints odd numbers
</code>

6. Practice exercises

Exercise 1: Find the maximum value in a list

<code>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)
</code>

Exercise 2: Count occurrences of each letter in a string

<code>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)
</code>

7. Advanced tips

ternary expression to simplify if‑else

<code>result = "Pass" if score >= 60 else "Fail"
# equivalent to:
if score >= 60:
    result = "Pass"
else:
    result = "Fail"
</code>

Nested loops (outer + inner)

<code>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)
</code>

8. Summary comparison table

PythonCode 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

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