【问题标题】:How to have if and elif in functions如何在函数中有 if 和 elif
【发布时间】:2016-01-09 18:22:17
【问题描述】:

首先。我的代码:

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

编辑:我发现可能很难看出我在问什么。

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

【问题讨论】:

  • 做什么工作?你的程序发生了什么?此外,缩进是 Python 中的 KEY。
  • 你不能在一个地方开始一个 if-elif 链,然后在另一个地方结束它。 Python 迫使你仔细缩进。如果这还不够帮助,您应该按照自己的方式学习 Python 教程,例如 this onethis one
  • 好的,我做了一个文字冒险,但很快就变成了重复,我想缩短重复。我将在我的原始代码中进行编辑。
  • ifelifelse 在函数中的工作方式与在函数外的工作方式相同。 def f(x): if x > 10 print "Big" else print "Small"
  • 我在原始代码中进行了编辑。

标签: python function python-3.x python-3.5 definitions


【解决方案1】:

如果您所有的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.'))

【讨论】:

    【解决方案2】:

    我找到了解决方案,完全停止使用 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2017-05-03
      • 2019-07-10
      • 2022-12-31
      • 1970-01-01
      相关资源
      最近更新 更多