Project
Guessing Num by Python
For this tutorial, we will create a simple guessing game where the computer generates a random number between 1 and 20, and the user has to guess the number within a certain number of tries.
Step 1: Import the necessary modules
The first thing we need to do is import the random
module to generate a random number. We also need to import the sys
module to be able to exit the game if the user wants to quit.
import random
import sys
Step 2: Generate a random number
Next, we need to generate a random number using the randint()
function from the random
module. We will store this number in a variable called number_to_guess
.
number_to_guess = random.randint(1, 20)
Step 3: Set the maximum number of tries
We will give the user a maximum of 5 tries to guess the correct number. We will store this number in a variable called max_tries
.
max_tries = 5
Step 4: Start the game loop
Now we will start the game loop that will continue until the user either guesses the correct number or runs out of tries. We will use a while
loop for this.
while max_tries > 0:
Step 5: Get the user’s guess
Inside the game loop, we need to ask the user to input their guess. We will use the input()
function to do this.
guess = input("Guess a number between 1 and 20: ")
Step 6: Convert the user’s guess to an integer
The input()
function returns a string, so we need to convert the user's guess to an integer using the int()
function.
guess = int(guess)
Step 7: Check if the user’s guess is correct
We will now compare the user’s guess to the number that the computer generated. If the guess is correct, we will print a message telling the user that they won and break out of the game loop. If the guess is incorrect, we will decrement the max_tries
variable and print a message telling the user how many tries they have left.
if guess == number_to_guess:
print("Congratulations, you won!")
break
else:
max_tries -= 1
print("Sorry, that's not the right number. You have", max_tries, "tries left.")
Step 8: End the game if the user runs out of tries
If the user runs out of tries, we will print a message telling them that they lost and exit the game using the sys.exit()
function.
if max_tries == 0:
print("Sorry, you ran out of tries. The number was", number_to_guess)
sys.exit()
Step 9: Run the game
Finally, we will run the game by putting all the code together.
import random
import sys
number_to_guess = random.randint(1, 20)
max_tries = 5
while max_tries > 0:
guess = input("Guess a number between 1 and 20: ")
guess = int(guess)
if guess == number_to_guess:
print("Congratulations, you won!")
break
else:
max_tries -= 1
print("Sorry, that's not the right number. You have", max_tries, "tries left.")
if max_tries == 0:
print("Sorry, you ran out of tries. The number was", number_to_guess)
sys.exit()
for the Next step Click here