如何在函数中使用 if 和 elif

How to have if and elif in functions

首先。我的代码:

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")

我不太擅长编码,所以这可能是我做错的地方

这个post好像有点公国,因为我几乎只有代码, 但我完全不知道如何让它工作。

代码没有缩短的样子:

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块都有相同的图案,你可以利用这个。

您可以为要打印的文本创建字典,然后取消 conditionals.When 选择要打印的文本,您只需使用相应的键获取相关文本即可。您使用 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")