Python Lesson 3: Understanding While Loops
A while loop allows you to repeat a block of code as long as a specified condition is true. While loops are commonly used when you don’t know how many iterations you need in advance.
1. What is a While Loop?
A while loop repeatedly executes a block of code as long as a given condition is true. The condition is checked before each iteration.
Syntax in Python:
while condition:
# Code to be executed as long as condition is trueExample:
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1 # Increment counterThis loop will print the value of counter 5 times, from 0 to 4, as long as the condition counter < 5 remains true.
2. Checking Conditions and User Input
You can use a while loop to repeatedly check a condition based on user input. For instance, you may want to keep asking the user for correct input until they provide it.
Example: Guessing Game
number_to_guess = 10
guessed_number = 0
while guessed_number != number_to_guess:
guessed_number = int(input("Enter the number to guess: "))
print("You guessed the correct number!")In this example, the program keeps asking the user for a number until they guess the correct one (10).
3. Adding if Statements Inside While Loops
You can add if statements inside a while loop to check additional conditions as the loop runs. This is useful for providing feedback or adding more logic within the loop.
Exercise 1: Fix the Code
Fix the provided code so that it gives feedback when the user enters the wrong number:
number_to_guess = 10
guessed_number = 0
while guessed_number != number_to_guess:
guessed_number = int(input("Enter the number to guess: "))
# TODO: Add an if statement to give feedback
# If guessed_number is greater than number_to_guess, print "Too high"
# Else if guessed_number is less than number_to_guess, print "Too low"
print("You guessed the correct number!")Exercise 2: Password Checker
Create a program that asks the user for a password and keeps asking until they enter the correct password (“secret”). Give feedback each time they enter the wrong password.
Example:
correct_password = "secret"
entered_password = ""
while entered_password != correct_password:
entered_password = input("Enter the password: ")
if entered_password != correct_password:
print("Incorrect password, try again.")
print("Access granted.")Exercise 3: Countdown Timer
Create a countdown program that asks the user for a starting number and counts down to 0. Each time the loop runs, print the current number.
Get Icodewithben’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
countdown = int(input("Enter a starting number: "))
while countdown > 0:
print(countdown)
countdown -= 1
print("Countdown complete!")Exercise 4: Coffee Machine Program
Make it so that the coffee machine keeps asking the user:
- Ask for the type of drink (1 for Coffee, 2 for Cappuccino, 3 for Latte).
- Ask for the quantity.
- Calculate the total cost based on the drink and quantity.
- Display the order details.
- Ask if they want to quit.
Exercise 5:
Create a simple calculator that asks the user for two numbers and an operation (addition, subtraction, multiplication, or division). Keep asking the user to perform calculations until they choose to exit the program.
Steps:
- Ask the user for two numbers.
- Ask the user for the operation they want to perform.
- Perform the operation and display the result.
- Ask if they want to perform another calculation (yes/no). If yes, repeat the process.
Homework: program these past paper questions and draw flowcharts
Extra: String Repeat
Training on Codewars
Write a function that accepts an integer n and a string s as parameters, and returns a string of s repeated exactly n times.
Examples (input -> output):
repeat_str(6, "I") # "IIIIII"
repeat_str(5, "Hello") # "HelloHelloHelloHelloHello"If you call your function below repeat_str(3, "*") it should return ***.
The function should look like this:
def repeat_str(n, s):
return ""






