Guess Number Mini Project
Guess Number Mini Project
Python Project to Learn
Write a Python game to guess a number. The script will generate a random number between 20 and 80 and ask the user to enter his guess. The code will continue to prompt the player for a guess until the correct number is input. It will provide feedback on each guess based on the difference between the guess and the correct number:
- If the difference between the input value and the correct number is greater than 12 the code will return “too low”.
- If the difference between the input value and the correct number is greater than -12 the code will return “too high”.
- If the difference between the input value and the correct number is less than 12 or -12 the code will return “hot”.
- If the user enters the correct number, display a congratulations message along with the number of attempts.
This is a fun Python project to learn and practice how to combine “while” loops, conditional statements and lists. See here more Python challenges.
Steps
- Use the
random.randint()function to generate a random number within the range of 20 and 80 and store it in the variable"prize". - Initialize the attempts equal to 0
- Inside a “while” loop, prompt the user to input their guess for the number using the
"input()"function. - Compare the user’s guess with the
prizeand provide feedback based on the difference. If the guess matches theprize, a congratulations message is displayed along with the number of attempts. If the guess is not correct, feedback is provided on whether the guess is too high, too low, or hot. - Continue to prompt the user for guesses until the correct number is guessed.
Expected output
Guess the number (between 20 and 80): 45 Too high Guess the number (between 20 and 80): 30 Hot Guess the number (between 20 and 80): 28 Congratulations! You guessed the number 28 correctly in 3 attempts
Solution
import random
# Generate a random number between 20 and 80
prize = random.randint(20, 80)
# Initialize the number of attempts
attempts = 0
# Ask the user to guess the number
while True:
guess = int(input("Guess the number (between 20 and 80): "))
attempts += 1 # Increment the number of attempts
# Compare the user's guess with the prize
difference = guess - prize
if difference == 0:
print(f"Congratulations! You guessed the number {prize} correctly in {attempts} attempts.")
break
elif difference > 12:
print("Too high")
elif difference < -12:
print("Too low")
else:
print("Hot")
