简体   繁体   English

Python while 循环不止一次询问输入

[英]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我一直在尝试通过猜测数字程序来解决这个问题,程序必须打印的第一个数字是 (Startlow + Starthigh)/2,然后 Ans 得到更新取决于输入

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我不明白为什么我的 while 循环会一直等待输入至少 2 次,直到它打印结果,即使我按 l 或 h(除非我按 c)这会中断循环

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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