在所有输入语句中获取输入选项而不重复if / elif / else语句

时间:2017-12-05 18:18:36

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

想知道是否有办法让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")

等等通过代码

2 个答案:

答案 0 :(得分: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()需要更复杂才能发挥作用 - 例如返回一个值或调用其他函数。

答案 1 :(得分:0)

你可以使用字典。

a = input("question: ")

a_dict = {'y': 'something', 's': 'save'}

if a in a_dict:
    print(a_dict[a])
else:
    print('not option')