繁体   English   中英

Python if循环无法正常运行/无效重复

[英]Python if loop doesn't function/repeats ineffectively

print("Guess a number between 1 and 100")  
userGuess = int(input("Your guess: "))   
import random      
randomNumber = (random.randint(1,100))

found = False

while userGuess in range(1,100):  
if userGuess > randomNumber:  
   int(input("Guess lower: "))  
   found = False  
elif userGuess < randomNumber:   
    int(input("Guess higher: "))  
    found = False  
else:  
    print("You got it!")      
    found = True  

在猜测数字时,在您第一次猜测之后,它将使用正确的上/下if / elif语句,但是此后的所有猜测将循环回到第一次使用的那个语句中。 最终即使我超出范围也重复同样的事情。 我知道该程序有很多这些线程,但是我不知道我的问题是什么,我们非常感谢您的帮助!

您的while循环没有任何内容。 缩进复合if语句使其成为循环的主体,即

while userGuess in range(1,100):  
    if userGuess > randomNumber:  
       int(input("Guess lower: "))  
       found = False  
    elif userGuess < randomNumber:   
        int(input("Guess higher: "))  
        found = False  
    else:  
        print("You got it!")      
        found = True

一旦有了这些,就需要修正您的逻辑。 最重要的是,每次输入错误后,您都需要接受一个新的UserGuess。 您的循环语句应该是

while not found:

您拥有的语句破坏了用户的输入值。

您没有在循环中将输入分配给userGuess

import random
print("Guess a number between 1 and 100")
randomNumber = random.randint(1,100)
userGuess = int(raw_input("Your guess: "))


print randomNumber
found = False

while 1:
    if userGuess < 1 or userGuess >100:
        userGuess =  int(input("input between 1 and 100 "))
        continue
    if userGuess ==  randomNumber:
        print("You got it!")
        break
    userGuess =  int(input("Guess lower: ")) if userGuess < randomNumber else int(input("Guess higher: "))

暂无
暂无

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

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