03. Iterations
03. Iterations
While & for-loops
Concept: More random numbers
For random floating-point numbers: Python's random module has random.random(), which returns a random float between 0.0 (inclusive) and 1.0 (exclusive). You can scale that yourself, e.g. random.random() * 10 gives a float from 0 up to (but not including) 10. randint(a, b) gives a random integer including both endpoints.
Exercise 1 β Countdown
Ask the user for a starting number.
Use a while loop to count down to zero.
When the countdown reaches zero, print:
GO!Example:
Starting number: 5
5
4
3
2
1
GO!Use time.sleep() so that the numbers don't appear immediately one after another, but leave one second between them.
Exercise 2 β Number guessing game
Create a random number between 1 and 100 using randint().
Ask the user to guess the number repeatedly.
After every guess, tell them:
Too highToo lowCorrect!
Keep asking until they guess correctly.
At the end, print how many attempts they needed.
Example:
Guess the number (1-100): 50
Too high!
Guess the number (1-100): 25
Too low!
Guess the number (1-100): 37
Correct!
You needed 3 attempts.Use a while loop and randint().
Exercise 3 β Password attempts
Create a program with a secret password.
The user gets three attempts to enter the correct password.
After each incorrect attempt, print how many attempts remain.
If the password is correct:
Login successful!If all three attempts are wrong:
Too many incorrect attempts.Then use:
sys.exit(1)to terminate the program.
If the login succeeds, terminate using:
sys.exit(0)Use while, if/else, ==, sys.exit() and input().
Exercise 4 β Dice rolling simulator
Ask the user how many dice they want to roll.
For each die:
- generate a random number between 1 and 6
- print the result
Afterwards, print the total.
For example:
How many dice? 5
Die 1: 4
Die 2: 6
Die 3: 2
Die 4: 5
Die 5: 1
Total: 18Use a for loop and range().
Then extend the program:
Ask whether the user wants to roll the dice again.
If they enter "yes", repeat the whole process.
This means you'll need a while loop containing a for loop.
Exercise 5 β ATM simulator
Write a small ATM program.
Start with:
balance = 1000Ask the user for their name and PIN.
The correct PIN is:
1234Give the user a maximum of three attempts to enter the PIN.
If the PIN is incorrect three times, print an error message to stderr:
Too many incorrect PIN attempts.and exit with:
sys.exit(1)After successfully logging in, repeatedly show a menu:
====================
ATM
====================
1. Show balance
2. Deposit money
3. Withdraw money
4. Exit
====================The user chooses an option.
- Option 1: Print the current balance.
- Option 2: Ask how much money they want to deposit and add it to the balance.
- Option 3: Ask how much they want to withdraw. Don't allow them to withdraw more than the current balance. If they try, print the error to the standard error output (sys.stderr).
- Option 4: Print a goodbye message and exit gracefully.
For an invalid menu option, print an error to stderr but keep the ATM running.
Exercise 6 β Lottery simulator
Create a lottery simulator.
Ask the user how many lottery tickets they want to play.
For every ticket, generate six random numbers between 1 and 45 and display them.
After all tickets have been generated, display the total number of tickets and the total number of numbers generated.
Then ask the user whether they want to generate another set of tickets.
If they answer "yes", start again.
If they enter anything else, print a goodbye message and end the program successfully.
Challenge: Make sure that each ticket contains six independently generated numbers.
Exercise 7 β Temperature monitoring
Write a program that simulates a temperature sensor.
Ask the user for:
- the minimum allowed temperature
- the maximum allowed temperature
- the number of measurements to simulate
Generate that number of random temperature measurements between 10 and 40 degrees. Use floating-point values rather than integers.
For every measurement, display:
- measurement number
- measured temperature
- whether the temperature is normal, too low, or too high
Keep track of how many measurements were:
- too low
- normal
- too high
At the end, display a summary such as:
Temperature report
------------------
Measurements: 10
Too low: 2
Normal: 6
Too high: 2If more than half of the measurements are outside the allowed range, print a warning message to the error output and terminate with an error status.
Otherwise, print that the sensor is operating normally.
Exercise 8 β Quiz game
Create a small quiz game.
The program should ask the user several multiple-choice questions.
For every question:
- display the question
- display four possible answers
- ask the user to choose an answer
- check whether the answer is correct
- keep track of the score
After every question, briefly wait before showing the next question.
At the end, calculate the percentage of correct answers.
Give the player a result:
- 90% or higher β
Excellent - 75β89% β
Very good - 50β74% β
Passed - below 50% β
Failed
Ask the player whether they want to play again.
If they choose "yes", start a new game with the score reset to zero.
If they enter anything else, end the program.
Exercise 9 β Guess the number: difficulty levels
Create a more advanced version of the number guessing game.
First, ask the user to choose a difficulty:
- Easy
- Medium
- Hard
The difficulty determines:
| Difficulty | Range | Maximum attempts |
|---|---|---|
| Easy | 1β20 | 10 |
| Medium | 1β100 | 7 |
| Hard | 1β500 | 5 |
Generate a random number within the selected range.
The player repeatedly enters guesses.
After every guess, tell them whether their guess is:
- too high
- too low
- correct
Keep track of the number of attempts.
If they guess correctly, display a success message including the number of attempts.
If they use all their attempts without guessing correctly, display the correct number and an error message.
Ask whether they want to play again.
Extra challenge: After every incorrect guess, also tell the player whether their guess was very close to the secret number. Decide yourself what "very close" means.
Exercise 10 β Mini command-line game
Create a small text-based adventure game.
The player starts with:
- a name
- 100 health points
- 0 gold
At the beginning, ask the player for their name.
Then repeatedly present a menu:
========================
Adventure Game
========================
1. Explore
2. Rest
3. Show status
4. Quit
========================Explore
When the player explores, generate a random event.
Possible events include:
- finding gold
- encountering an enemy
- finding nothing
- finding a healing potion
Finding gold increases the player's gold.
An enemy causes random damage.
A healing potion restores some health, but health may never exceed 100.
Display what happened.
Rest
Resting restores some health.
However, resting should take a few seconds, with a short pause before the player is told that they have recovered.
Show status
Display:
- player name
- health
- gold
Use a ternary expression to indicate whether the player is currently "Healthy" or "Injured".
Quit
Display a goodbye message and terminate successfully.
Game over
If the player's health reaches zero, print an appropriate message to the error output and terminate with an error status.
The game should continue running until the player quits or dies.
Break and continue
Exercise 1 β Input validator
Create a program that repeatedly asks the user to enter a positive integer.
The program should:
- accept the number if it is valid
- reject invalid input
- keep asking until the user enters a valid number
- stop immediately when a valid number has been entered
Afterwards, print the number and whether it is even or odd.
Then ask the user whether they want to enter another number.
Use continue to skip the rest of the current iteration when the input is invalid, and break when the program should leave the loop.
Also handle a special input where the user enters "quit" to leave the program immediately.
Exercise 2 β Shopping list calculator
Create a small shopping calculator.
Repeatedly ask the user for the price of an item.
The user can enter:
- a positive number β add it to the total
0β stop entering products- a negative number β reject it and ask again
"quit"β immediately stop the program
Keep track of:
- number of valid products
- total price
- highest price
- lowest price
Invalid negative prices should not affect any of these values.
At the end, print a receipt containing the number of products, total price, average price, highest price and lowest price.
If no products were entered, print an appropriate message instead of trying to calculate an average.
Exercise 3 β Number analysis
Ask the user how many numbers they want to enter.
Then repeatedly ask for that many numbers.
For every number:
- if it is negative, ignore it and continue with the next number
- if it is zero, stop processing numbers immediately
- otherwise, process it normally
For the numbers that were actually processed, calculate:
- how many numbers were entered
- how many were even
- how many were odd
- the total
- the average
- the largest number
- the smallest number
At the end, display a report.
For example:
Numbers processed: 7
Even numbers: 4
Odd numbers: 3
Total: 126
Average: 18.0
Smallest: 4
Largest: 42The zero should end the input process, while negative numbers should simply be skipped.
Exercise 4 β Random number challenge
Create a game in which the computer generates random numbers between 1 and 100.
The player has to guess whether the next number will be higher or lower than the current number.
For example:
Current number: 47
Will the next number be higher or lower? higher
Next number: 82
Correct!
Current number: 82
Will the next number be higher or lower? lower
Next number: 91
Wrong!Keep playing until:
- the player gives a wrong answer
- two consecutive random numbers are equal
- the player chooses to quit
Keep track of the player's score.
After every correct prediction, increase the score and continue the game.
If the player enters an invalid answer, don't generate a new number. Ask the question again.
At the end, print the final score.
Exercise 5 β Simple download manager
Simulate downloading a number of files.
Ask the user how many files they want to download.
For every file:
- ask for the filename
- generate a random download time between 1 and 5 seconds
- display that the download has started
- wait the generated number of seconds
- randomly decide whether the download succeeds or fails
- display the result
If a download fails, skip the remaining processing for that file and continue with the next file.
The user should also be able to enter "cancel" instead of a filename. In that case, stop all remaining downloads immediately.
At the end, display:
- number of files successfully downloaded
- number of failed downloads
- number of canceled downloads
- total number of files processed
Use continue when a download fails and break when the user cancels the entire download process.
Extra challenge: Before starting the downloads, ask the user whether they want to see the simulated waiting times. If they answer "no", still perform the waits, but don't display the individual waiting times.