Python Number Guessing Game: A Beginner's Coding Project
import random
def guess_number():
number = random.randint(1, 100)
attempts = 0
print('Welcome to the Number Guessing Game!')
print('I\'m thinking of a number between 1 and 100.')
while True:
guess = int(input('Take a guess: '))
attempts += 1
if guess < number:
print('Too low! Try again.')
elif guess > number:
print('Too high! Try again.')
else:
print(f'Congratulations! You guessed the number in {attempts} attempts.')
break
guess_number()
This Python code implements a simple number guessing game. Here's how it works:
- Generate a Random Number: The code starts by importing the
randommodule and usingrandom.randint(1, 100)to generate a random number between 1 and 100. - Game Loop: The game runs within a
while Trueloop, allowing the player to keep guessing until they get it right. - Get User Input: Inside the loop, the program prompts the user to enter their guess using
input('Take a guess: '). The input is converted to an integer usingint(). - Check the Guess: The code then compares the user's guess to the randomly generated number:
- If the guess is too low, it prints 'Too low! Try again.'
- If the guess is too high, it prints 'Too high! Try again.'
- If the guess is correct, it prints a congratulatory message along with the number of attempts and breaks out of the loop.
This simple game is a great way to practice Python basics like loops, conditional statements, user input, and working with the random module. You can modify and expand upon this code to create more challenging variations of the game!
原文地址: https://www.cveoy.top/t/topic/fvVF 著作权归作者所有。请勿转载和采集!