对于循环,在达到条件之前结束

时间:2019-08-25 14:23:59

标签: python

我正在尝试做一个数字猜谜游戏,规则是您要获得10个猜谜才能找到随机生成的数字。它将显示您的猜测是否太高/太低,如果正确,程序将结束。但是由于某种原因,即使我猜错了,程序也结束了。如果有人可以解决我的问题,将不胜感激。

Actions ac= new Actions(driver);
ac.DragAndDrop(source, destination).Build().Perform();

2 个答案:

答案 0 :(得分:2)

break将直接退出循环

import random  


rand = random.randint(1,100)  
guesses = 0  

for i in range(10):  
    guess = int(input("Guess the secret number"))  
    if guess > rand:  
        print("your guess is too high")  
        guesses += 1  
        print("number of guesses",guesses,"/10")  
    if guess < rand:  
        print("your guess is too low")  
        guesses +=1  
        print("number of guesses",guesses,"/10")  
    if guess == rand:  
        print("you won")
        break # <- move break under the correct if statement

答案 1 :(得分:0)

break语句用于终止当前循环。因此,当您使用它时,它将结束当前循环,并将控件传递给循环之后的语句。

在您的情况下,由于您已将break语句放在for循环的末尾,因此该循环在第一次迭代中终止。

因此,您所能做的就是将break语句放在最后一个if条件内,如下所示

import random  


rand = random.randint(1,100)  
guesses = 0  

for i in range(10):  
    guess = int(input("Guess the secret number"))  
    if guess > rand:  
        print("your guess is too high")  
        guesses += 1  
        print("number of guesses",guesses,"/10")  
    if guess < rand:  
        print("your guess is too low")  
        guesses +=1  
        print("number of guesses",guesses,"/10")  
    if guess == rand:  
        print("you won")  
        break