首先关闭。我的代码:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
我不擅长编码,所以这可能是我做错的事情
这篇文章看起来有点公,因为我几乎只有代码, 但我完全不知道如何做这项工作。
代码看起来没有缩短:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
编辑:我看到可能很难看出我在问什么。
我想知道如何缩短原始代码
答案 0 :(得分:0)
如果所有elif
块都具有相同的模式,您可以利用此功能。
您可以为要打印的文本创建字典,然后取消条件。当选择要打印的文本时,只需使用相应的键获取相关文本即可。您使用get(key, default)
方法。如果字典中没有key
,则返回默认值。例如,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
答案 1 :(得分:0)
我找到了一个解决方案,完全停止使用elif。
示例:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")