打破(或制动)这个特定代码中的循环 - Python

Break (or brake) a loop in this specific code - Python

我试图创建一个 "end" 变量,它应该会中断(或制动)但它显然不起作用。

我的作业题目:

修改上面的程序,只给用户5次猜测。如果猜测超过 5 次,用户应收到以下消息:(在代码中)

第一个代码运行完美,但在这个代码中,while 循环只是重复。

# Welcome message
print("Welcome to the Magic Ball!")

# The magic number
answer = 7

# Prepares "end" variable
end = False

# Take guess
guess = int(input("\nYour guess: "))

# While loop

# While guess NOT EQUAL to ANSWER, re-ask
# And add whever too high or too low
# Used a boolean to tell the program when to stop the loop
while guess != answer or end == True:
    for guess in range(1, 5, +1): # For loops limits ammount of guesses
        guess = int(input("\nYour guess: "))
    if guess > answer:
        print("\nToo high")
    elif guess < answer:
        print("\nToo low")
    # If still not completed, print "max chances"
    print("You have gotten to your maximum answers")
    # This ends the loop so it stops going around
    end = True

# If loop passed, tell the user it's correct
# After printing "max chances", the Python will print this out,
# So make sure the answers match
if guess == answer:
    print("\nWell done")

您在 while 循环中有一个 for 循环,这是多余的。你应该选择一个或另一个。如果你想在猜到正确答案时停止循环,你只需要将你的 if 语句(当前在最后)移动到循环内。

此外,您的 range() 中不需要“+1”,因为 1 是默认值。

第一个问题是你的while循环逻辑不对

应该是:

while guess != answer and not end:

下一个问题是您的 for 循环正在循环询问 4 个答案,但它从不打印提示,因为这些打印语句的缩进太低。

此外,您可能根本不想在 while 循环中使用 for 循环,只需选择一种循环类型或另一种循环即可。如果使用 while 循环,则需要一个计数器来记录猜测的次数。

另一个明显的问题是,您使用 guess 作为 for 循环迭代器,但随后您使用用户的输入对其进行了重置。这太糟糕了!

这是使用 for 循环的代码,这可能是最好用的循环类型,因为它不需要像在 while 循环中那样递增计数器变量。

# Welcome message
print("Welcome to the Magic Ball!")

# The magic number
answer = 7

for _ in range(5):
    guess = int(input("\nYour guess: "))
    if guess == answer:
        break
    elif guess > answer:
        print("Too high")
    elif guess < answer:
        print("Too low")
if guess == answer:
    print("Well done!")
else:
    print("You have used all your guesses")
print("The answer was {}".format(answer))

您正在使用两个循环而不是一个循环 - 要么只使用 for 循环,要么实际使用 while 循环。

这是一种可能性(只使用 while 循环,我也没有测试这个):

# While guess NOT EQUAL to ANSWER, re-ask
# And add whever too high or too low
# Used a boolean to tell the program when to stop the loop
tries = 1
while (not guess == answer) and (not tries == 5):
    guess = int(input("\nYour guess: "))
    if guess > answer:
        print("\nToo high")
    elif guess < answer:
        print("\nToo low")
    else:
        tries += 1
    if tries == 5:
        print("You have gotten to your maximum answers")