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

时间:2015-03-04 23:14:31

标签: python while-loop break

我试图创造一个"结束"变量,应该破坏(或制动),但它显然不起作用。

我的作业中的问题:

修改上面的程序,只给用户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")

3 个答案:

答案 0 :(得分:1)

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

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

答案 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))

答案 2 :(得分:0)

你使用的是两个循环而不是一个循环 - 或者只使用for循环,或者实际上在循环时使用你。

这是一种可能性(仅使用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")