简体   繁体   中英

Python while loop ask more than once for input

I've been trying to solve the issue with guessing the number program, The first number the program has to print Ans which is (Startlow + Starthigh)/2 and then Ans gets updated depends on the input

I can't figure out why my while loop keeps waiting for the input for at least 2 times until it prints the results even if I press l or h (unless I press c) which breaks the loop

Startlow = 0
Starthigh = 100
Ans = (Startlow + Starthigh)/2
print("Please think of a number between 0 and 100!")

while True:
    print("Is your secret number " + str(int(Ans)))
    if input() == "c":
        print("Game over,Your secret number was: "+str(int(Ans)))
        break
    elif input() == "l":
        Startlow = Ans
        Ans = (Startlow + Starthigh)/2
    elif input() == "h":
        Starthigh = Ans
        Ans = (Startlow + Starthigh)/2
    else:
        print("Sorry, I did not understand your input.")

any help appreciated :)

You should be asking for input once in the loop, and then comparing that answer to the items you want.

You are instead requesting a (potentially different) answer at each of your conditionals.

The number of questions asked depends on how many conditionals you fall through.

Just do:

x = input()
if x == "c":
  #And so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM