Bear with me, I am a beginner.
Here is my code for a simple version of Guessing Game. I know that it can be written in a way more efficient way, but please help and let me know why what I wrote isn't working. Not matter what letter I type, h
, or l
, it keeps on looping over the first letter that I picked.
high = 100
low = 0
guess = ((low high) / 2)
print("Please think of a number between" str(high) " and " str(low))
answer = input("Is your secret number " str(guess) "?\n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
while guess != 0:
if answer == "h":
high = guess
guess = ((low high) / 2)
input("Is your secret number " str(guess) "?\n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
elif answer == "l":
low = guess
guess = ((low high) / 2)
input("Is your secret number " str(guess) "?\n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
elif answer == "c":
print("Game over. Your secret number was " str(guess))
break
else:
print("Sorry, I did not understand your input."
"Is your secret number " str(guess) "?\n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
CodePudding user response:
You need to put the line answer = input("Is your secret number ...")
inside the while loop, so that each time, the program gets a new input. This would be:
...
while guess != 0:
answer = input("Is your secret number ...")
if answer == 'h':
...
I also recommend you use f-strings to print out numbers, so instead of:
print("Please think of a number between" str(high) " and " str(low))
you can just write:
print(f"Please think of a number between {high} and {low}")
To learn more about f-strings, check out this page.