python - 最大错误答案后如何停止循环?
问题描述
这是 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")
解决方案
欢迎来到社区,我们尝试在这里讨论问题,而不是寻找完整的解决方案。
我建议您首先学习编程的基础知识,例如决策制定、控制流(即 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()
推荐阅读
- android - 多个dex文件定义 Lcom/google/protobuf/AbstractMessageLite$Builder$LimitedInputStream;
- magento - Magento 2.3 不发送任何电子邮件
- excel - 在子文件夹中打开文件
- gtk - gtk(mm) 3 锚定在文本视图中的文本视图无法将光标移入
- node.js - 可以使用 Reac-native 项目建立到 .net mvc wsdl 的服务连接吗
- java - Fitnesse 中的身份验证不适用于网页
- javascript - 可以在变量中分配 URL 地址并在 HTML 中使用。使用 JavaScript?
- c++ - 为什么我的 switch 语句不能正常工作?
- iis - IIS 中的 ASP.Net core 2.2 部署问题
- c# - UWP 创建应用程序包在发布模式下失败