Python - 16
Python - 16: Random Numbers & Simple Games
Python can generate random numbers, which is useful for games, simulations, and unpredictable results.
Your challenge: Generate a random number, build a simple guessing game, and compare the player's guess with the secret number.
Import the random module
Use import random so your program can use Python's random-number tools.
Generate a random number
random.randint(1, 10) returns a random whole number from 1 through 10, including both ends.
Convert the player's guess
input() gives you text, so use int(guess) before comparing the answer with a number.
Check the result
Use an if statement to check whether the guess matches the secret number. Use else for the incorrect answer.
Try it: Change the guessing range from 1 to 5 to 1 to 10.
Good Python habit: Make sure the range shown in the question matches the range used in random.randint().
👀 Show Example Solution
import random
number = random.randint(1, 10)
print("Random Number:")
print(number)
secret = random.randint(1, 5)
guess = input("Guess a number from 1 to 5: ")
if int(guess) == secret:
print("Correct!")
else:
print("Wrong!")
print("The secret number was:")
print(secret)The program creates a random secret number, converts the player's answer to an integer, and compares the two values.
