python - 即使我将变量设置为重新启动它,循环也不会重新启动
问题描述
我对 python 很陌生,并决定尝试基于文本的冒险作为学习基础知识的起始项目。
如果用户输入了错误的单词,我有这个 while 循环会以 var valid_input 重新启动。它可以工作,但我注意到即使它应该已经重新启动,它仍然会读取最后的 else 语句,并给出一个额外的打印,我只打算在用户输入错误操作时显示。
while valid_input == False:
dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
if dec2 == "light":
if "lighter" in inventory:
print(">You use the lighter to light up the room")
print(">You find yourself in a large cavernous structure")
room_visible = 1
valid_input = True
break
else:
print(">You don't seem to have anything to light up the place.")
valid_input = False
if dec2 == "shout":
print(">You shout at the top of your lungs and see what that does.")
valid_input = True
break
else:
print("Invalid action")
valid_input = False
更新#1
我修复了代码并尝试正确缩进,因为这是建议。尽管它仍然打印出“无效操作”消息,但这对我来说很有意义。
我决定在 else 语句中随机放置一个 valid_input = True ,它似乎有效。这是当前有效的代码,尽管我不明白它为什么有效。希望有人能解释一下!
while valid_input == False:
dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
if dec2 == "light":
if "lighter" in inventory:
print(">You use the lighter to light up the room")
print(">You find yourself in a large cavernous structure")
room_visible = 1
valid_input = True
break
else:
valid_input = True
print(">You don't seem to have anything to light up the place.")
valid_input = False
elif dec2 == "shout":
print(">You shout at the top of your lungs and see what that does.")
valid_input = True
break
else:
print("Invalid action")
valid_input = False
解决方案
最后if dec2=="shout" ... else ...
是在代码块里面if dec2=="light"
。如果用户输入“light”,则将执行此 if-else 组合。因为dec2
是light
,所以不是shout
,因此解释器进入else
块并打印"Invalid action"
。
您可能需要以下代码
while valid_input == False:
dec2 = input("Do you shout aloud or try to use something to light the place (shout/light)")
if dec2 == "light":
if "lighter" in inventory:
print(">You use the lighter to light up the room")
print(">You find yourself in a large cavernous structure")
room_visible = 1
valid_input = True
break
else:
print(">You don't seem to have anything to light up the place.")
valid_input = False
elif dec2 == "shout":
print(">You shout at the top of your lungs and see what that does.")
valid_input = True
break
else:
print("Invalid action")
valid_input = False
推荐阅读
- node.js - 如何在 Lerna 中导入外部项目
- javascript - 如何在 puppetter javascript 中嵌套 $$eval?
- pytorch - 在 Pytorch 中使用带有一个热向量的交叉熵损失的正确方法
- php - 教义无法连接到数据库
- google-apps-script - Google 表单脚本设置选项值的行为将不需要的“,”添加到源中的字符串
- mongodb - mongodb查找方法,如果已经存在则不添加数据
- python - 自定义 spacy NER 模型在测试 2400 个示例后停止
- python - Pythonic dict,其值为 list()
- progressive-web-apps - 如何根据添加到后台同步或删除的请求处理 Workbox v4 中的事件
- html - 如何以角度获取更新的html元素