Python - Control Flow

Hey there, future Python pros! Today, we're diving into the exciting world of control flow in Python. Think of control flow as the traffic lights of programming - it directs the flow of your code, telling it when to go, stop, or take a detour. Let's get started!

Python - Control Flow

Decision Making Statements

Imagine you're at an ice cream shop. You have to decide: chocolate or vanilla? This is exactly what decision-making statements do in Python - they help your program make choices.

The 'if' Statement

The 'if' statement is the simplest form of decision making. Here's how it works:

ice_cream_flavor = "chocolate"

if ice_cream_flavor == "chocolate":
    print("Yum! Chocolate is my favorite!")

In this example, if the ice_cream_flavor is "chocolate", it will print the message. If it's not, nothing happens.

The 'if-else' Statement

But what if we want to do something when the condition isn't true? That's where 'else' comes in:

age = 15

if age >= 18:
    print("You can vote!")
else:
    print("Sorry, you're too young to vote.")

Here, if the age is 18 or older, it prints "You can vote!". Otherwise, it prints the other message.

The 'if-elif-else' Statement

Sometimes, we need to check multiple conditions. That's where 'elif' (short for 'else if') comes in handy:

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Need improvement")

This code checks the score and prints the corresponding grade.

Loops or Iteration Statements

Loops are like a merry-go-round for your code. They let you repeat actions without writing the same code over and over.

The 'for' Loop

The 'for' loop is great when you know how many times you want to repeat something:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I love {fruit}!")

This loop will print "I love [fruit]!" for each fruit in the list.

The 'while' Loop

The 'while' loop keeps going as long as a condition is true:

count = 0

while count < 5:
    print(f"Count is {count}")
    count += 1

This will print the count from 0 to 4.

Jump Statements

Jump statements are like secret passages in a video game - they let you skip parts of your code or exit loops early.

The 'break' Statement

'break' lets you exit a loop immediately:

for i in range(10):
    if i == 5:
        print("Found 5! Exiting loop.")
        break
    print(i)

This will print numbers from 0 to 4, then exit when it finds 5.

The 'continue' Statement

'continue' skips the rest of the current iteration and moves to the next one:

for i in range(5):
    if i == 2:
        print("Skipping 2")
        continue
    print(i)

This will print all numbers from 0 to 4, except 2.

The 'pass' Statement

'pass' is like a placeholder. It does nothing, but it's useful when you need empty code blocks:

for i in range(5):
    if i == 2:
        pass  # TODO: Add special handling for 2
    else:
        print(i)

This will print all numbers except 2, where it does nothing (for now).

Putting It All Together

Now, let's combine these concepts into a fun little game:

import random

secret_number = random.randint(1, 10)
attempts = 0

while True:
    guess = int(input("Guess the number (1-10): "))
    attempts += 1

    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print(f"You got it in {attempts} attempts!")
        break

    if attempts == 3:
        print(f"Sorry, you've run out of attempts. The number was {secret_number}.")
        break

This game uses a while loop, if-elif-else statements, and the break statement to create a number guessing game. It's a great example of how control flow can create interactive programs!

Summary

Here's a quick reference table of the control flow statements we've covered:

Statement Purpose
if Make a decision based on a condition
if-else Choose between two options
if-elif-else Choose between multiple options
for Repeat code a specific number of times
while Repeat code while a condition is true
break Exit a loop early
continue Skip to the next iteration of a loop
pass Do nothing (placeholder)

Remember, mastering control flow is like learning to conduct an orchestra - it gives you the power to create complex, beautiful programs from simple instructions. Keep practicing, and soon you'll be writing Python symphonies!

Credits: Image by storyset