【问题标题】:Getting a input option to happen in all input statements without repeating if/elif/else statments在不重复 if/elif/else 语句的情况下,在所有输入语句中获取输入选项
【发布时间】:2017-12-06 02:28:21
【问题描述】:

想知道是否有一种方法可以让 python 在输入语句中接受“save”或“s”,以便在每次将其输入到 .py 文件中的任何 if/elif/else 时执行某些操作,所以我不知道不必重复 if/elif/else 几次。我想要这样的东西

a=input("some other question that i want to accept s/save: ")
b=input("Again but i dont want 2 if statments: ")

而不是。

a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")
print("A bunch of other code for 100 lines")
a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")

等通过代码

【问题讨论】:

  • 试试dictionary
  • 功能不就是为了这个吗? def ask_question(): ...
  • ?我不明白

标签: python python-3.x if-statement python-3.6


【解决方案1】:

把重复的代码放在一个函数中,多次调用该函数:

def ask_question(q):
    a=input(q)
    if a == "y":
        print("something")
    elif a == "y":
        print("Something")
    elif a in ("s", "save")
        print("save")
    else:
        print("not option")

# now

ask_question("first question")

print("A bunch of other code for 100 lines")

ask_question("second question")

当然,您的 ask_question() 需要更复杂才能有用 - 例如返回一个值或调用其他函数。

【讨论】:

    【解决方案2】:

    你可以使用字典。

    a = input("question: ")
    
    a_dict = {'y': 'something', 's': 'save'}
    
    if a in a_dict:
        print(a_dict[a])
    else:
        print('not option')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      相关资源
      最近更新 更多