Python Flow Control

Flow Control

Flow control in Python allows you to control the execution of your code based on conditions, loops, or specific rules. This capability is fundamental for writing dynamic and responsive programs.

Boolean Values

Boolean values in Python represent one of two states: `True` or `False`. Unlike integers, floating-point numbers, or strings, which can have infinite possible values, the Boolean data type is binary. For instance, you can compare two numbers using Boolean operators to determine if they are equal or not:

a = 3
b = 5
print(a == b)  # False
print(a != b)  # True

Comparison Operators

Python provides a set of comparison operators to compare values:

Operator Meaning
`==` Equal to
`!=` Not equal to
`<` Less than
`>` Greater than
`<=` Less than or equal to
`>=` Greater than or equal to

For example:

print('dog' != 'cat')  # True
print(100 == '100')    # False
print(100 > 90)        # True

Boolean Operators

Boolean operators like `and`, `or`, and `not` are used to combine or invert Boolean expressions. They enable complex conditional logic:

print((4 < 5) and (10 < 11))  # True
print((4 < 5) and (10 > 11))  # False
print((4 < 5) or (10 > 11))   # True
print(not (4 < 5))            # False
print(2 + 2 == 4 and not 2 + 2 == 5 and 'dog' != 'cat')  # True

If-Elif-Else Statements

Conditional statements in Python allow you to execute code based on conditions. The `if-elif-else` structure is commonly used for such cases:

name = 'David'
age = 3000
if name == 'Paul':
    print('The dune awaits.')
elif age < 15:
    print('You are not ready for the dune yet.')
else:
    print('You are neither Paul nor ready for the dune.')
You are neither Paul nor ready for the dune.

While Loop Statements

Loops allow you to execute a block of code multiple times. A `while` loop continues running as long as its condition is `True`. Compare the behavior of `if` and `while`:

spam = 0
if spam < 5:
    print(f'Hello, world {spam}.')
    spam = spam + 1
Hello, world 0.

Versus:

spam = 0
while spam < 5:
    print(f'Hello, world {spam}.')
    spam = spam + 1
Hello, world 0.
Hello, world 1.
Hello, world 2.
Hello, world 3.
Hello, world 4.

Breaking from a While Loop

The `break` statement allows you to exit a loop prematurely when a specific condition is met:

spam = 0
while spam < 5:
    print(f'Hello, world {spam}.')
    if spam == 3:
        break
    spam = spam + 1
Hello, world 0.
Hello, world 1.
Hello, world 2.
Hello, world 3.

For Loop

A `for` loop iterates over a sequence (like a list or range) and executes the code block for each element:

spam = 0
for spam in range(5):
    print(f'Hello, world {spam}.')
    if spam == 3:
        break
Hello, world 0.
Hello, world 1.
Hello, world 2.
Hello, world 3.

Collection of Data: Range

The `range` function generates a sequence of numbers. It is powerful for creating collections or iterating over indices. For example:

s = 'Paul Atreides'
for i in range(len(s)):
    print(i, s[i])
0 P
1 a
2 u
3 l
4
5 A
6 t
7 r
8 e
9 i
10 d
11 e
12 s

You can also reverse the range:

s = 'Paul Atreides'
for i in reversed(range(len(s))):
    print(i, s[i])
12 s
11 e
10 d
9 i
8 e
7 r
6 t
5 A
4
3 l
2 u
1 a
0 P

While and For Loops in Practice

Here’s a practical example of loops in action: calculating the value of spice based on its weight and price per gram:

pricePerGram = 1_000_000
weight = input("How many grams of spice do you have?: ")
value = int(weight) * pricePerGram
print(value)

You can refine this with validation to ensure the user inputs a valid weight:

def spiceValue():
    pricePerGram = 1_000_000
    while True:
        weight = input("How many grams of spice do you have?: ")
        if weight.isdigit():
            weight = int(weight)
            if weight > 0:
                break
            else:
                print("Amount must be greater than 0.")
        else:
            print("Please enter an integer number.")
    return weight * pricePerGram

spiceValue()

Putting It All Together: Fizz Buzz Game

The Fizz Buzz game is a classic example of conditional logic and loops:

  • Players count upwards from 1.
  • If a number is divisible by 3, say "Fizz".
  • If divisible by 5, say "Buzz".
  • If divisible by both, say "FizzBuzz".

Here’s how you can implement it in Python:

while True:
    n = input("Enter the number to count to: ")
    if n.isdigit():
        n = int(n)
        if n > 0:
            break
        else:
            print("Number must be positive.")
    else:
        print("Please enter an integer number.")
for i in range(1, n+1):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)