CODING180
Chapter 1 of 612m

Control Flow Fundamentals for Python Coding

Control Flow Fundamentals for Python Coding

If Chapter 2 gave you the pieces, this chapter shows you how to make them move.

We’ll steer your programs with comparisons, Boolean logic, conditionals, and loops.

They will react to input and repeat work for you.

By the end, you’ll make classic patterns like FizzBuzz and a small guessing loop.

We’ll also highlight indentation, block structure, and truthiness.

These are core habits of clean python coding.

We’ll mention the python coding language once more to anchor your mental model.

Then we will focus on practical skills.

What you’ll learn

  • Make decisions with comparisons and Boolean logic
  • Use if/elif/else with proper indentation
  • Loop with for (and range) and while
  • Avoid common errors like off-by-one and infinite loops

Comparisons and Boolean Logic in Python Coding

Comparisons evaluate to True or False:

x = 10
print(x == 10)   # True (equality)
print(x != 5)    # True (not equal)
print(x > 7)     # True (greater than)
print(x >= 10)   # True (greater or equal)
print(x < 3)     # False

You can combine conditions with Boolean operators:
- and: both must be True
- or: at least one is True
- not: flips True/False

age = 20
has_ticket = True

can_enter = (age >= 18) and has_ticket  # True if both conditions are True
print(can_enter)

discount = (age < 18) or (age >= 65)    # True if either condition is True
print(discount)

print(not has_ticket)  # False

Truthiness

In python coding, values can act as True or False in conditionals:
- Falsey: 0, 0.0, empty strings "", empty containers ([], {}, ()), None
- Truthy: almost everything else

items = []
if items:
    print("We have items!")
else:
    print("List is empty")  # This runs because [] is falsey

If/Elif/Else: Choosing a Path

Indentation defines blocks in Python.

Use 4 spaces per level.

The colon starts a block.

Indentation groups the statements that belong together.

score = 83

if score >= 90:
    grade = "A"
elif score >= 80:  # Checked only if the previous condition was False
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D or F"

print(grade)

Tip: Keep conditions mutually exclusive and ordered from most restrictive to least.

This helps avoid accidental matches.

Loops in Python Coding: for, range, and while

Loops repeat work.

Two main loop types:

for + range

Use for to iterate over sequences.

The range function generates a sequence of numbers you can loop over.


for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

for i in range(2, 10, 2):
    print(i)  # 2, 4, 6, 8

Watch out for off-by-one errors.

range(5) goes 0..4, not 0..5.

When you need N iterations, range(N) is your friend.

You can also iterate over strings, lists, and more:

for ch in "cat":
    print(ch)  # c, a, t

while loops

while repeats while a condition is True.

Change something inside the loop.

Otherwise, it may run forever.

count = 3
while count > 0:
    print("Countdown:", count)
    count -= 1  # Move toward stopping condition
print("Blast off!")

break and continue

  • break exits the loop immediately.
  • continue skips to the next iteration.
for n in range(10):
    if n % 2 == 0:
        continue        # Skip evens
    if n > 7:
        break           # Stop the loop
    print(n)            # Prints 1, 3, 5, 7

Indentation and Block Structure

Python uses indentation to show structure.

No braces required.

Consistency matters:
- Use 4 spaces (not tabs) per level.
- Every block after a colon (:) must be indented equally.
- Misaligned blocks raise IndentationError or behave unexpectedly.

total = 0
for i in range(3):
    total += i   # Inside the loop
print(total)      # Outside the loop (prints 3)

Practical Exercises

Before you dive in, a quick note.

If you don’t have Python installed, you can run and test the examples for this chapter in one of these top Python online IDEs.

Exercise 1: FizzBuzz

Write a program that prints numbers from 1 to 20.

For multiples of 3, print "Fizz"; for multiples of 5, print "Buzz"; for multiples of both, print "FizzBuzz".

Expected outcome: A list of lines like 1, 2, Fizz, 4, Buzz, Fizz, …, 14, FizzBuzz, …

Starter hint:

for n in range(1, 21):
    if (n % 3 == 0) and (n % 5 == 0):
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Tips:
- Put the combined condition first; otherwise 15 will match the 3 or 5 case early.
- range(1, 21) includes 1..20 (stop is exclusive).

Exercise 2: Number Guessing (Limited Attempts)

Pick a secret number between 1 and 20 (hardcode it or use random).

The user gets 5 attempts.

After each guess, hint “Too low” or “Too high.”

Stop early if they guess correctly.

Starter hint:

secret = 13  # or: import random; secret = random.randint(1, 20)
max_attempts = 5

attempt = 1
while attempt <= max_attempts:
    guess = int(input(f"Attempt {attempt}/{max_attempts} - Your guess: "))
    if guess == secret:
        print("You got it! 🎉")
        break  # Exit the loop early
    elif guess < secret:
        print("Too low.")
    else:
        print("Too high.")
    attempt += 1

if attempt > max_attempts and guess != secret:
    print(f"Out of attempts! The number was {secret}.")

Tips:
- Make sure attempt increases every loop.
- Compare integers, not strings, wrap input with int(...).

Troubleshooting: Common Control Flow Gotchas

  • Off-by-one errors: Remember range(stop) stops before stop. Example: range(5) yields 0..4. If you need 1..5, use range(1, 6).
  • Infinite loops: Ensure your while loop condition will eventually be False. Modify the loop variables inside the loop.
  • Indentation errors: Mixed tabs/spaces or misaligned blocks cause errors or surprising behavior. Configure your editor for 4 spaces.
  • Never-reached code: If/elif chains run top-down; a broad condition early can shadow later conditions.

Want more practice right away? To keep building your control flow skills in python coding, try more beginner-friendly challenges in these Python exercises for beginners.

Mini-Quiz (3 quick checks)

1) What does range(2, 7) produce?
- A) 2, 3, 4, 5, 6
- B) 2, 3, 4, 5, 6, 7
- C) 3, 4, 5, 6, 7

2) Which line prevents an infinite loop?
- A) while x > 0: print(x)
- B) while x > 0: x -= 1
- C) while True: pass

3) Which values are falsey?
- A) 0, "", []
- B) 1, "0", [0]
- C) True, "False", (1,)

(Answers: 1-A, 2-B, 3-A)

Where you’re headed next

In the next chapter, we’ll bundle logic into reusable pieces in Chapter 4: Functions and Modules for Python Coding Beginners.

Then you’ll meet the core containers you’ll loop over day-to-day in Chapter 5: Data Structures and Files in Python Coding, and bring everything together in Chapter 6: Build a Mini Project in the Python Coding Language.

Summary & Additional Resources

Key takeaways:
- Comparisons and Boolean logic return True/False and drive decisions.
- if/elif/else chooses one path; order and indentation matter.
- for with range handles counted loops; while repeats while a condition stays True.
- Watch for off-by-one errors and make sure while loops terminate.

You now have the essential control structures to write interactive, responsive programs in the python coding language.

Additional Resources:
- Python control flow tutorial (official docs), Authoritative explanations and more examples of if/elif/else, for, while, break, and continue.