
Python is a great language for beginners to learn programming. One of the fun things you can do with Python is develop simple games. In this tutorial, we will learn how to develop a simple game in which the user has to guess a number.
The game we will create will work as follows: the computer will generate a random number between 1 and 100. The user will then be asked to guess the number. If the user's guess is too high or too low, the computer will give a hint. The game will continue until the user guesses the correct number.
To start, we need to import the random module, which will allow us to generate a random number. Then, we will use the randint() function to generate a random number between 1 and 100. We will also create a variable to keep track of the number of guesses the user has made.
import random
number = random.randint(1, 100)
guesses = 0
Next, we will create a while loop that will continue until the user guesses the correct number. Inside the loop, we will ask the user to enter a guess using the input() function. We will also increment the number of guesses the user has made.
while True:
guess = int(input("Guess the number between 1 and 100: "))
guesses += 1
Inside the loop, we will also add an if statement to check if the user's guess is correct. If the guess is correct, we will print a message congratulating the user and telling them how many guesses it took to win. We will also break out of the loop.
if guess == number:
print("Congratulations, you guessed the number in", guesses, "guesses!")
break
If the guess is incorrect, we will add an else statement that will give the user a hint. If the guess is too high, we will tell the user to guess lower. If the guess is too low, we will tell the user to guess higher.
else:
if guess < number:
print("Guess higher.")
else:
print("Guess lower.")
Here's the complete code for the game:
import random
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(input("Guess the number between 1 and 100: "))
guesses += 1
if guess == number:
print("Congratulations, you guessed the number in", guesses, "guesses!")
break
else:
if guess < number:
print("Guess higher.")
else:
print("Guess lower.")
This is a simple game that can be easily extended to make it more challenging. For example, you can add a limit to the number of guesses the user can make, or you can add a scoring system based on the number of guesses it takes to win. Have fun exploring and experimenting with Python!