【问题标题】:How do I perform a proper if function in this case?在这种情况下如何执行正确的 if 函数?
【发布时间】:2020-02-20 19:06:48
【问题描述】:

在给程序一个定义的字符串(例如“add”)之后,这段代码让我问第一个 if input(x) 问题。 输入几次后,它给了我想要的输出。

为什么不在第一次尝试? 另外,当输入为“end”时,如何执行程序结束等循环?

提前谢谢你。 最好的。

    x = """Wählen Sie eine der folgenden vorgegebenen Operationen: (add/subtract/multiply/divide/end/history)
"""
a = "Erste Zahl: "
b = "Zweite Zahl: "
ops = ["add", "subtract", "multiply", "divide", "history", "end"]
list = []

if input(x) in ops:

    list.append(input(x))

    if input(x) == "add":
        print(int(input(a)) + int(input(b)))

    elif input(x) == "subtract":
        print(int(input(a)) - int(input(b)))

    elif input(x) == "multiply":
        print(int(input(a)) * int(input(b)))

    elif input(x) == "divide":
        print(int(input(a)) / int(input(b)))

    elif input(x) == "history":
        print(list)

    elif input(x) == "end":
        print("Das Programm wird beendet")

else:
    print("""Geben Sie bitte eine gültige Eingabe ein""")

【问题讨论】:

  • 您反复拨打input()。将变量命名为 list 是个糟糕的主意,要小心!

标签: python if-statement input


【解决方案1】:

每次您拨打input() 时,您都在要求 输入。您可能只想一次调用input(),将结果保存在一个变量中,然后与该变量进行比较:

answer = input("Please type your answer ")

if answer == "hello":
    print("You typed a greeting")
elif answer == "hamburger":
    print("You are eating lunch")
... etc

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2012-06-06
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多