关于计算器程序的问题在Python 3中重复的num1和num2 for else

时间:2018-03-12 13:19:10

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

我决定编制一个计算器,但我的问题是,如果我做了选择并输入6,它仍然会向我询问 num1 在说"输入无效之前,请先检查选择操作并再试一次!"。我想要的是它直接说"输入无效,请检查选择操作并再试一次!"无需请求 num1 num2 。我希望它清楚。

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

计算器()

1 个答案:

答案 0 :(得分:0)

更正了您的代码,请阅读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))