# "Number guessing game" in Python

I am new to Python and I have tried to come up with a code for the number guessing game. But I am pretty sure this is not the right way to do it. I am able to get the right output, however, my code is pretty long. Any ideas on using a different logic or to reduce the code size would help.

I also would like to know how to code profile a python code for performance.

I am using IDLE and Python 3.+

import random

def main():
while(True):
inputchoice = input("Are you ready? Y/N : ")
if(inputchoice.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
print("Ok. Lets begin")
randomnumberguessinggame()
break
elif(inputchoice.strip() in ("no","No","NO","nO","n","N")):
print("Let me know when you are ready")
break
else:
print("Invalid Entry. Try again")

def randomnumberguessinggame():
actualnumber = random.randrange(0,1000)
#print("The number to be guessed is %d"%actualnumber)
flag = True;
while(flag):
try:
guessednumber = int(input("Enter your guess "))
if(guessednumber > actualnumber):
print("That was a wrong guess. Your guess is higher than my number")
while(True):
retry = input("Would you like to try again? Y/N : ")
if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
flag = True;
break
elif(retry.strip() in ("no","No","NO","nO","n","N")):
flag = False;
break
else:
print("Invalid Entry. Try again")
elif(guessednumber < actualnumber):
print("That was a wrong guess. Your guess is lower than my number")
while(True):
retry = input("Would you like to try again? Y/N : ")
if(retry.strip() in ("y","Y","yes","Yes","YES","YEs","yeS","YeS","yEs","yES")):
flag = True;
break
elif(retry.strip() in ("no","No","NO","nO","n","N")):
flag = False;
break
else:
print("Invalid Entry. Try again")
else:
print("You've got it right. Congratulations!!")
flag = False;
except ValueError:
print("Your guess is invalid. Kindly guess again.")
flag = True;

main()

print("Exiting the game...")

• Small point: Why not replace the inputchoice.strip() in ("y","Y","yes"," ...) by just inputchoice.strip().lower().startswith('y')? Feb 4 '17 at 13:40
• @JohnColeman Feel free to point that out in an answer. As for the reason? Beginners usually don't know such thing :-)
– Mast
Feb 4 '17 at 18:17

I would not abuse the user with the question whether he wants to continue; just have a command (say, quit) for quitting the game while still guessing.

randomnumberguessinggame

The Python way is random_number_guessing_game.

You don't have to use parentheses in the branch and loop conditionals.

Summa summarum

import random

def main():
actual_number = random.randrange(0, 1000)
while True:
guess = input("Enter your guess: ")

if guess.strip().lower() == "quit":
print("Bye!")
return

try:
guess_number = int(guess)
except ValueError:
print(guess, "is not an integer!")
continue

if guess_number < actual_number:
elif guess_number > actual_number:
else:
print(guess_number, "Excellent!")
return

main()


Hope that helps.

For starters, remove all the semicolons, this is not Java or C#. Furthermore, You can extract a function that handles all the questions for confirmation. Next, why not consider every answer that is not a confirmation as a 'no' if you choose to ask that many times which I wouldn't.

I'd write it as follows:

import random

def play():
guessing_game(random.randrange(0, 1000))
print("Congratulations!! Exiting the game...")

def guessing_game(number):
try:
guess = int(input("Enter your guess: "))
if guess == number:
return
print(["Higher!", "Lower!"][guess > number])
except ValueError:
print("Invalid!")
guessing_game(number)

if __name__ == '__main__':  # this the proper way
play()

• @Graipher I wouldn't argue with the loop ;-) But since the OP asked to reduce code size (not to improve performance, memory footprint or readability), I went with the recursion. Feb 4 '17 at 15:38
• Fair enough. Anyways, you already got my +1 for your first sentence. Feb 4 '17 at 15:40