首页 > 解决方案 > 最大错误答案后如何停止循环?

问题描述

这是 OCW MIT 的 CompSci 和 Python 编程简介中的一个练习。我稍微修改了一下。问题是当我达到最大错误答案时我想停止程序但是如果我尝试两次它就会停止。为什么两次?我怎样才能解决这个问题 ?作为一个新手,我应该在这里问每一个问题吗?谢谢大家

n = 0
max_guesses = 3
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")

if n == "left" or "Left":
    print("You're out of lost forest")
while n == "right" or n == "Right":
    n = input("You are in the Lost Forest\n****************\n******       ***\n  :(\n****************\n****************\nGo left or right? ")
    n =+ 1
    for n in range (max_guesses):
        break
print("Game over! You ran out of your lives")

标签: pythonpython-3.xwhile-loop

解决方案


欢迎来到社区,我们尝试在这里讨论问题,而不是寻找完整的解决方案。

我建议您首先学习编程的基础知识,例如决策制定、控制流(即 if 语句和循环)。此外,尝试在运行时使用不同的逻辑和输入多次尝试这个问题。它会让你更好地理解逻辑分析。

这是您可以添加逻辑的方法之一。

#Maximum allowed guesses
max_guesses = 3

def func1():
    
    #Input string 'left' or 'right'
    in_str = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
    
    #Number of attempts made
    n = 1
    
    if in_str.lower() == "left":
        print("You're out of lost forest")
    
    while in_str.lower() == "right":
        in_str = input("You are in the Lost Forest\n****************\n******       ***\n  :(\n****************\n****************\nGo left or right? ")
        n += 1
        if in_str.lower() == "left":
            print("You're out of lost forest")
            break
        if n >= max_guesses:
            print("Game over!!!")
            break
    
    print("Total attempts made by user: ",n)
    
func1()


推荐阅读