【发布时间】:2013-10-11 05:57:53
【问题描述】:
1.我正在使用break 跳出循环,但我不知道如何让程序继续运行,除非发生这种情况。只输入while: 是无效的(或者程序告诉我),我希望即使用户输入空字符串,游戏也能继续运行。
2.有没有一种方法可以不必每次我需要时都重新输入一些代码?我有一堆响应要程序吐出,我将不得不多次使用:
if action[0]=='go':
print("You're supposed to go to David!")
elif action[0]=='look':
print("You can't see that")
elif action[0]=='take':
print("You don't see the point in taking that.")
else:
print("I don't recognise that command")
其中action 是来自玩家输入的列表。还是我每次都必须重新输入?
我不知道如何定义一个执行上述操作的函数,我什至不确定这是我应该做的。
3.我使用的一些故事描述很长,我不希望玩家不得不横向滚动太多。但我只想将它们定义为变量以节省一些打字时间。有没有解决的办法。还是我只需要每次都用
print(“““a string here”””)
4.如果字符串以“look”开头并且包含“floor”或“mess”或“rubbish”,我希望它打印某个输出。这是我目前拥有的:
if action[0]=='look':
if 'floor' in action or 'rubbish' in action or 'trash' or 'mess' in action:
print('onec')
elif 'screen' in action or 'computer' in action or 'monitor' in action:
print('oned')
elif 'around' in action or 'room' in action or 'apartment' in action:
print('onee')
elif 'david' in action or 'tyler' in action or 'boy' in action or 'brat' in action or 'youth' in action:
print('onef')
break
else:
print("You can't see that")
它为任何以'look' 开头的输入打印'onec'。
【问题讨论】:
-
#4 中的问题是
... or 'trash' or 'mess' in action等价于... or ('thrash') or ('mess' in action),并且像'trash'这样的非空字符串总是评估为true;因此第一个条件总是满足的。您可以通过执行if any(x in action for x in ['floor', 'rubbish', 'trash', 'mess'])之类的操作来使其更短更简洁 - 这会检查action是否包含列表中的任何单词。
标签: python string variables loops printing