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...")
2 Answers 2
Advice 1
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.
Advice 2
randomnumberguessinggame
The Python way is random_number_guessing_game
.
Advice 3
You don't have to use parentheses in the branch and loop conditionals.
Summa summarum
I had this in mind:
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:
print("Your guess is too small.")
elif guess_number > actual_number:
print("Your guess is too large.")
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():
print("Get ready to start guessing!")
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()
-
\$\begingroup\$ @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. \$\endgroup\$user2390182– user23901822017年02月04日 15:38:22 +00:00Commented Feb 4, 2017 at 15:38
-
\$\begingroup\$ Fair enough. Anyways, you already got my +1 for your first sentence. \$\endgroup\$Graipher– Graipher2017年02月04日 15:40:21 +00:00Commented Feb 4, 2017 at 15:40
Explore related questions
See similar questions with these tags.
inputchoice.strip() in ("y","Y","yes"," ...)
by justinputchoice.strip().lower().startswith('y')
? \$\endgroup\$