0

首先关。我的代码:

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

编辑:我看到可能很难看到我在问什么。

我想知道如何缩短我的原始代码

4

2 回答 2

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")
于 2016-01-10T14:43:33.240 回答
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.'))
于 2016-01-10T01:03:14.613 回答