【问题标题】:Issues on Calculator Program of repeated num1 and num2 for else in Python 3Python 3 中 else 重复 num1 和 num2 的计算器程序问题
【发布时间】:2018-03-12 13:19:10
【问题描述】:

我决定编写一个计算器,但我的问题是,如果我做了一个 选择 并输入 6,它仍然要求我输入 num1num2 在说“无效输入,请检查选择操作并重试!”之前。我想要的是它直接说“无效输入,请检查选择操作并重试!”无需请求 num1num2。我希望它很清楚。

def calculator():
def add(x, y):
    return x + y

def sub(x, y):
    return x - y

def mul(x, y):
    return x * y

def div(x, y):
    return x / y

print(""" -- Select Operation --
1. Addition
2. Subtraction
3. Multiplication
4. Division
""")

choice = input("Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
print("\n")
print("Calculating...")
num1 = int(input("Enter First number >> "))
num2 = int(input("Enter Second number >> "))

if choice == '1':
    print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
    print(num1, "-", num2, "=", add(num1, num2))
elif choice == '3':
    print(num1, "-", num2, "=", add(num1, num2))
elif choice == '4':
    print(num1, "-", num2, "=", add(num1, num2))
else:
    print("Invalid Input, PLease check the *Select Operation* and Try Again!")

计算器()

【问题讨论】:

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


    【解决方案1】:

    更正你的代码请阅读python语法

    def add(x, y):
        return x + y
    
    def sub(x, y):
        return x - y
    
    def mul(x, y):
        return x * y
    
    def div(x, y):
        return x / y
    
    print(""" -- Select Operation --
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
    """)
    
    choice = input("Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
    while(choice not in ('1','2','3','4')):
      choice = input("Invalid Input Please Enter 1 or 2 or 3 or 4 from the Select Operation >> ")
    print("\n")
    print("Calculating...")
    num1 = int(input("Enter First number >> "))
    num2 = int(input("Enter Second number >> "))
    
    if choice == '1':
        print(num1, "+", num2, "=", add(num1, num2))
    elif choice == '2':
        print(num1, "-", num2, "=", sub(num1, num2))
    elif choice == '3':
        print(num1, "-", num2, "=", mul(num1, num2))
    elif choice == '4':
        print(num1, "-", num2, "=", div(num1, num2))
    

    【讨论】:

    • 谢谢,它成功了。我想我还在尝试理解 while 循环,我需要更多的例子。
    • 请接受@EmpressObazee的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    相关资源
    最近更新 更多