Today you will apply everything you have learned in a small project:
input)if, elif, else)while)random module for generating random numbersBy the end, you will have a fully working guessing game that reacts to user input.
Python can generate random numbers using the random module.
import random → include the module
random.randint(1, 10) → number between 1 and 10
import random
number = random.randint(1, 10)
Now Python knows: number is a random number between 1 and 10.
We want the game to continue until the player guesses correctly.
For that, we use a while loop.
guess = 0 # starting value
while guess != number:
guess = int(input("Guess the number from 1 to 10: "))
Explanation:
guess == numberint() converts the input into a numberWe give hints:
guess < number → "Too low!"guess > number → "Too high!"
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Correct!")
import random
number = random.randint(1, 10)
guess = 0
while guess != number:
guess = int(input("Guess the number from 1 to 10: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Correct!")
We want to know how many attempts the player needed.
Start attempt counter: attempts = 0
Increase with each guess: attempts = attempts + 1
Print at the end: print("You needed X attempts")
import random
number = random.randint(1, 10)
guess = 0
attempts = 0
while guess != number:
guess = int(input("Guess the number from 1 to 10: "))
attempts = attempts + 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Correct! You needed", attempts, "attempts!")
This small project demonstrates:
input()if / elif / elserandom module for random numbers