我试图创建一个“结束”变量,它应该中断(或制动),但显然没有起作用。在
我作业中的问题:
用户只需猜测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
循环循环请求4个答案,但它从不打印提示,因为这些print语句的缩进太低。在另外,您可能根本不想在while循环中使用for循环,只需选择一种类型的循环。如果使用while循环,则需要一个计数器来跟踪猜测次数。在
另一个突出的问题是,您使用
guess
作为for循环迭代器,但随后使用用户的输入重置它。这太糟糕了!在下面是使用for循环的代码,这可能是最好的循环类型,因为它消除了在while循环中增加计数器变量的需要。在
^{pr2}$您使用的是两个循环而不是一个循环-要么只使用for循环,要么实际上利用while循环。在
有一种可能(只使用while循环,我也没有测试):
在while循环中有一个for循环,这是多余的。你应该选一个。如果您想在猜测正确答案的情况下停止循环,只需将If语句(当前位于最末尾)移动到循环中。在
另外,range()中不需要“+1”,因为默认值是1。在
相关问题 更多 >
编程相关推荐