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():
print("Get ready to start guessing")
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...")
inputchoice.strip() in ("y","Y","yes"," ...)
by justinputchoice.strip().lower().startswith('y')
? \$\endgroup\$