🔀 Day 3: Conditions & Loops

Making Decisions and Repeating Actions

📚 What You'll Learn Today

Today you'll learn how to make your programs make decisions and repeat actions:

🎯 Interactive Number Guesser

Try this Python-powered number guessing game! It uses exactly what you'll learn today:

🔧 Python Concepts in Action:

🔀 If/Else Statements Compares your guess to the secret number
🔄 While Loops Keeps asking until you guess correctly
📊 Boolean Logic True/False conditions control the game
🎮 User Input Handles your guesses and validates input
🖥️ Open Full Screen Demo

🔀 If Statements

Use if statements to execute code only when certain conditions are true.

Basic Syntax:

if condition: # This code runs if condition is True print("This happens!")

With else:

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

With elif (else if):

score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") else: print("Grade: F")
Grade: B
💡 Remember: Python uses indentation (spaces at the start of lines) to define code blocks. Use 4 spaces per level!

⚖️ Comparison Operators

Compare values using these operators:

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 3 < 5 True
>= Greater than or equal 5 >= 5 True
<= Less than or equal 3 <= 5 True
⚠️ Important: Use == to compare, not =. = is for assignment, == is for comparison.

🔗 Boolean Logic

Combine conditions using and, or, and not.

and - Both must be true:

age = 25 has_license = True if age >= 21 and has_license: print("You can drive!") else: print("You cannot drive.")
You can drive!

or - At least one must be true:

day = "Saturday" if day == "Saturday" or day == "Sunday": print("It's the weekend!") else: print("It's a weekday.")
It's the weekend!

not - Reverses the condition:

is_raining = False if not is_raining: print("No rain - go outside!") else: print("Bring an umbrella!")
No rain - go outside!

🔄 While Loops

Repeat code while a condition is true.

Basic while loop:

count = 1 while count <= 5: print("Count:", count) count += 1 # Same as: count = count + 1 print("Blast off!")
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Blast off!
⚠️ Warning: Be careful with while loops! If the condition never becomes False, the loop will run forever. Press Ctrl+C to stop it.

📊 For Loops

Loop through a sequence (like a list or range).

Using range():

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

With start and end:

# range(1, 6) gives: 1, 2, 3, 4, 5 for i in range(1, 6): print("Number:", i)
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5

Looping through a list:

colors = ["red", "green", "blue"] for color in colors: print("Color:", color)
Color: red Color: green Color: blue

🛠️ Step-by-Step Building Guide

Follow these steps to build your own number guessing game:

Step 1: Import Required Libraries

# number_guesser.py - Start with imports import random def main(): """Main game function""" secret_number = random.randint(1, 100) guess = 0 attempts = 0 print("🎯 Number Guessing Game") print("I'm thinking of a number between 1-100") while guess != secret_number: guess = int(input("Enter your guess: ")) attempts += 1 if guess < secret_number: print("Too low! Try higher.") elif guess > secret_number: print("Too high! Try lower.") print(f"🎉 Correct! Got it in {attempts} tries!") if __name__ == "__main__": main()

Step 2: Add Input Validation

def get_valid_guess(): """Get and validate user input""" while True: try: guess = int(input("Enter guess (1-100): ")) if 1 <= guess <= 100: return guess print("Please enter 1-100!") except ValueError: print("Please enter a valid number!")

Step 3: Add Game Loop with Attempts Counter

def play_game(): secret_number = random.randint(1, 100) attempts = 0 max_attempts = 10 print(f"🎯 Guess the number (1-100) in {max_attempts} tries!") while attempts < max_attempts: attempts += 1 guess = get_valid_guess() if guess == secret_number: print(f"🎉 Got it in {attempts} tries!") return if guess < secret_number: print("🔺 Too low!") else: print("🔻 Too high!") print(f"💥 Game Over! The number was {secret_number}")

Step 4: Add Hint System

def get_hint(secret_number, attempts, max_attempts): """Provide strategic hints""" remaining = max_attempts - attempts if remaining <= 2: return f"Very close! Only {remaining} tries left!" elif attempts >= 3: if secret_number > 50: return "The number is higher than 50" else: return "The number is lower than 50" return "Keep trying!"
🎯 Key concepts you're learning:
  • while loops - Keep going until condition is met
  • if/elif/else - Make decisions based on conditions
  • boolean logic - True/False conditions control flow
  • input validation - Handle user errors gracefully
  • random numbers - Generate unpredictable values

🏋️ Exercise: Number Guessing Game

Create a program where the computer picks a random number and you have to guess it!

# Here's a starter - complete the logic: secret_number = 7 guess = 0 # Ask for user input and check if guess is correct # Tell them if their guess is too high or too low # Keep asking until they get it right!

Bonus Challenge:

Count how many guesses it took and print "You got it in X guesses!"

# Example solution: secret_number = 7 guess = 0 attempts = 0 while guess != secret_number: guess = int(input("Guess a number: ")) attempts += 1 if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") else: print("You got it!") print("Guesses:", attempts)

✅ Key Takeaways

🎉 Ready for Day 4?

Tomorrow you'll learn about functions - writing reusable code!

Marking complete will unlock Day 4!