Writing simple games in python is a great way to practice conditional statements and loops. In this article, we will implement a guessing game in python using if-else blocks and while loop.
What is the Guessing Game?
The guessing game that we are going to implement in python has simple rules.
- First, the program generates a random number between 1 and 99.
- Then, it asks the user to guess the number.
- If the user enters a number less than the number generated by the system, the system tells the user that the guess is low. It then asks the user to guess the number again.
- If the number entered by the user is greater than the system-generated number, the system tells the user that guessed number is larger. It then asks the user to guess the number again.
- If the user guesses the number correctly, the system informs to the user and the game ends.
How to Implement the Guessing Game in Python?
We will use the following steps to create the guessing game.
- First, we will use the randint() function from the random module in python to generate a random number between 1 and 99.
- Next, we will use the input() function to take the number guessed by the user as input.
- After this, we will use a while loop to implement the program logic. Inside the while loop, we will use the if-else block to check the conditions for user input.
- If the user guesses the number correctly, we will use a break statement to come out of the while loop and end the program.
Following is the complete code to implement the guessing game in Python.
import random
n = random.randint(1, 99)
guess = int(input("Enter an integer from 1 to 99: "))
while True:
if guess < n:
print ("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("you guessed it right! Bye!")
break
Output:
Enter an integer from 1 to 99: 23
guess is low
Enter an integer from 1 to 99: 45
guess is low
Enter an integer from 1 to 99: 67
guess is low
Enter an integer from 1 to 99: 89
guess is low
Enter an integer from 1 to 99: 98
you guessed it right! Bye!
Conclusion
In this article, we have discussed how to create a guessing game in python. To learn more about python programming, you can read this article on the hangman game in python. You might also like this article on string manipulation in Python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.