In our previous Python tutorial, we have explained to make a Dice Rolling Simulator in Python. In this tutorial, we will Make Guess Game in Python.
Python is a popular language among developers as it’s a first choice of beginners to learn and do amazing things. Here in this tutorial, we will code a project for beginners. We will make a Guess Game using random
and math
module from python.
So let’s code our game:
Implement Guess Game
First we will import Python module random
and math
to use in our guest game.
import random import math
We will get user input number as lower bound and upper bound to get number between using random.randint()
function.
lowerBound = int(input("\nEnter Lower bound number:")) upperBound = int(input("\nEnter Upper bound number:")) numberBetween = random.randint(lowerBound, upperBound)
We will take guess number as user input and loop through to check if guess number is matched or it is high or low and display message.
guessCounter = 0 while guessCounter < math.log(upperBound - lowerBound + 1, 2): guessCounter += 1 guessNumber = int(input("\nGuess a number:- ")) if numberBetween == guessNumber: print("\nCongratulations you did it in ", guessCounter, " try") break elif numberBetween > guessNumber: print("\nYou guessed too small!") elif numberBetween < guessNumber: print("\nYou guessed too high!")
Finally, we will check if guess counter greater than and display the mssage with number.
if guessCounter >= math.log(upperBound - lowerBound + 1, 2): print ("\nThe number is %d" % numberBetween) print("\nHave better luck next time!")
Complete Code
Here is complete code of our Guess Game in Python.
import random import math lowerBound = int(input("\nEnter Lower bound number:")) upperBound = int(input("\nEnter Upper bound number:")) numberBetween = random.randint(lowerBound, upperBound) print ("\n\tYou've only ", round(math.log(upperBound - lowerBound + 1, 2)), " chances to guess the integer!\n") guessCounter = 0 while guessCounter < math.log(upperBound - lowerBound + 1, 2): guessCounter += 1 guessNumber = int(input("\nGuess a number:- ")) if numberBetween == guessNumber: print("\nCongratulations you did it in ", guessCounter, " try") break elif numberBetween > guessNumber: print("\nYou guessed too small!") elif numberBetween < guessNumber: print("\nYou guessed too high!") if guessCounter >= math.log(upperBound - lowerBound + 1, 2): print ("\nThe number is %d" % numberBetween) print("\nHave better luck next time!")
Output:
Enter Lower bound number:4 Enter Upper bound number:8 You've only 2 chances to guess the integer! Guess a number:- 5 You guessed too small! Guess a number:- 6 You guessed too small! Guess a number:- 7 Congratulations you did it in 3 try The number is 7 Have better luck next time!