我得到一个错误,该选项未在计算器函数中定义

2024-04-26 10:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

函数的第24行第10行出现问题。它说选择是没有定义的

我已经尝试更改与每个运算符相关的定义变量和整数变量

def start():
    print("Hey, I'm your calculator... \n")

    num1 = float(input("Enter your first number: "))
    num2 = float(input("Enter your second number: "))
    print("Operator list: \n 1. Addition + \n 2. Subtraction - \n 3. Multiply * \n 4. Division / \n")
    choice = int(input("Type the letter corresponding to your selection: "))

add = 1
subtract = 2
multiply = 3
divide = 4

def calculate():
    if choice == add or 1:
        print(num1 + num2)
    elif choice == subtract or 2:
        print(num1 - num2)
    elif choice == multiply or 3:
        print(num1 * num2)
    elif choice == divide or 4:
        print(num1 / num2)
    else:
        print("Oops! Please enter a valid operator: '+', '-', '*', or '/'")
        start()

start()
calculate()

回溯(最近一次呼叫最后一次):

File "C:/Users/hkben/OneDrive/Desktop/PythonFiles/calculator.py", line 29, in calculate() File "C:/Users/hkben/OneDrive/Desktop/PythonFiles/calculator.py", line 16, in calculate if choice == add or 1: NameError: name 'choice' is not defined


Tags: oraddinputyour定义deffloatcalculator