首先。我的代码:
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")
编辑:我知道可能很难明白我在问什么。
我想知道如何缩短我的原始代码
如果所有的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.'))
我找到了一个解决方案,只是完全停止使用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")