🐍 Python Course 8: Simple Loops

🎯 Learning Objectives

After completing this section, you will understand:

⚡ Prerequisites

  • Understanding of variables
  • Knowledge of conditional statements
  • Basic arithmetic operations

1. While Loops

A while loop executes a block of code repeatedly as long as a condition is true:

# Basic while loop counter = 1 while counter <= 5: print(counter) counter += 1
1 2 3 4 5
📝 Exercise 1: Simple Counter (1 point)

Write a while loop that counts from 1 to 5:

# Write your code here counter = 1 while counter <= 5: print(counter) counter += 1

2. Loop Conditions

The loop condition determines how long the loop continues:

📝 Exercise 2: Password Checker (1 point)

Create a program that keeps asking for a password until "secret" is entered:

# Write your code here password = "" while password != "secret": password = input("Enter password: ") print("Correct password!")

3. Common Loop Patterns

Here are some common patterns you'll use with while loops:

📝 Exercise 3: Sum Calculator (1 point)

Write a program that calculates the sum of numbers from 1 to 5:

# Write your code here sum = 0 i = 1 while i <= 5: sum += i i += 1 print(f"Sum: {sum}")

4. Avoiding Infinite Loops

An infinite loop occurs when the loop condition never becomes False:

📝 Exercise 4: Number Guessing (1 point)

Create a number guessing game that stops when the user guesses 42:

# Write your code here secret_number = 42 guess = 0 while guess != secret_number: guess = int(input("Guess the number: ")) if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") print("Correct!")

🎉 Summary

You've learned about:

Total points: 4/4

⬅️ Previous

Course 7: More conditionals