A simple guessing game in Python explained here.
Sure! Let’s create a simple guessing game in Python where the player has to guess a randomly chosen number. Here’s a step-by-step explanation:
Game Outline:
- The game randomly selects a number between 1 and 100.
- The player has to guess the number.
- The game will give hints if the guess is too low or too high.
- The game continues until the player guesses the correct number.
- After the correct guess, the game tells the player how many attempts it took.
Python Code:
import randomdef guessing_game(): # Step 1: Randomly select a number between 1 and 100 number_to_guess = random.randint(1, 100) attempts = 0 guessed = False print("Welcome to the Guessing Game!") print("I'm thinking of a number between 1 and 100.") # Step 2: Start the game loop while not guessed: # Step 3: Get player's guess try: player_guess = int(input("Take a guess: ")) except ValueError: print("Please enter a valid number.") continue # Step 4: Count the attempt attempts += 1 # Step 5: Check if the guess is correct if player_guess < number_to_guess: print("Too low! Try again.") elif player_guess > number_to_guess: print("Too high! Try again.") else: guessed = True print(f"Congratulations! You've guessed the correct number in {attempts} attempts.")# Run the gameguessing_game()
Explanation:
- Importing the
random
module:
random.randint(1, 100)
is used to generate a random number between 1 and 100.
- Game Loop:
- The game runs in a
while
loop until the correct number is guessed. - The loop keeps track of the number of attempts.
- User Input:
- The player’s guess is taken using
input()
and converted to an integer. - If the input is not a valid number, the game asks the player to try again.
- Hints:
- The game provides hints if the guess is too low or too high.
- End Condition:
- The loop ends when the player guesses the correct number, and the game congratulates the player, showing the number of attempts.
This is a basic yet fun game that helps beginners understand loops, conditionals, and user input in Python!