Blog
Guess The Number!
- Harshit
- July 18, 2020
- 7:55 am
- No Comments
A simple game code to compete with your computer to guess the right random number!
Welcome to the code! This code is for you beginners who are keen to learn python programming and also have fun with python.
In this code, a random number will be guessed using the random module. The player has to guess the number and even the computer will be guessing the number in the backdrop. One who guesses the number with less number of steps is the winner!
Note: Loved the post? You too can publish your article on “Python for fun” which will be loved by millions. Contribute an article!
import random
def computerguess(lowerval, higherval, randnum, count=0): #lowerval is 0 & higherval is 100 and this function is called in print statement of line 47
if higherval >= lowerval:
guess = lowerval + (higherval - lowerval) // 2
#guess is in the middle(guess is equal to the random generated number), it is found!
if guess == randnum:
return count
#guess is greater than the randum number
#count is increased by one
#The next guess should be between the lowest number and present guess
elif guess > randnum:
count = count + 1
return computerguess(lowerval, guess-1, randnum, count)
#guess is less than the random number
#count is increased by one
#The next guess should be between the highest number and present guess
else:
count = count + 1
return computerguess(guess+1, higherval, randnum, count)
else:
#number not found, coz lowval is never greater than highval
return -1
#end of function
#generate a random number between 1 to 100
randnum = random.randint(1,101)
count = 0
guess = -99
while (guess != randnum):
#Get the user's guess
guess = (int)(input("Enter your guess between 1-100: "))
if guess > randnum:
print("Choose a lower number")
elif guess < randnum:
print("Choose a higher number")
else:
print("You guessed it right!")
break #shouldn't count when te guess got right
count = count + 1
#end of while loop
print("You took " + str(count) + " steps to guess the right number")
print("Computer took " + str(computerguess(0,100,randnum)) + " steps to guess the right number")
if str(count) < str(computerguess(0,100,randnum)): print("Congratulations!! You won!") elif str(count) > str(computerguess(0,100,randnum)):
print("Oopsss!! You lost.. Better luck next time.")
else:
print("Wow!! That's a Tie! You are no less than computer.")
5
2
votes
Rating
Subscribe
Login
0 Comments
Inline Feedbacks
View all comments