0

I have been working on this bit of code and every time I run it it says that result was not defined.

Error: Traceback (most recent call last):
  File "/Users/Bubba/Documents/Jamison's School Work/Programming/Python scripts/Ch9Lab2.py", line 24, in <module>
    print(str(numberOne) + " " + operation + " " + str(numberTwo) + " = " + str(result))
NameError: name 'result' is not defined

Original Code:

def performOperation(numberOne, numberTwo):
    if operation == "+":
        result = numberOne + numberTwo
    if operation == "-":
        result = numberOne - numberTwo
    if operation == "*":
        result = numberOne * numberTwo
    if operation == "/":
        result = numberOne / numberTwo

numberOne = int(input("Enter the first number: "))
numberTwo = int(input("Enter the second number: "))
operation = input("Enter an operator (+ - * /): ")

performOperation(numberOne, numberTwo)

print(str(numberOne) + " " + operation + " " + str(numberTwo) + " = " + str(result))
2
  • 2
    result is not in the global scope. it's in the performOperation scope. if you want the result, return it from your function and store the returned value when you call the function, Commented Apr 3, 2017 at 20:46
  • If you're attempting to make a calculator, why not just use the exec function? Example: while True:exec('print('+input('Enter the equation: ')+')') - Exec is a function that runs code that is in the form of a string. The example takes input such as "9+9" and then outputs the solution to your calculation. Commented Apr 3, 2017 at 20:58

2 Answers 2

1

You'll need to use the return keyword to use the variable result outside the function

def performOperation(numberOne, numberTwo):
    ...
    return result

result = performOperation(numberOne, numberTwo)
Sign up to request clarification or add additional context in comments.

Comments

0

The variable 'result' is only defined in the scope of your function. If you want to print it out, you should assign the result of the performOperation function to the result variable. Also, make sure you actually return something in your function.

def performOperation(numberOne, numberTwo):
    if operation == "+":
        result = numberOne + numberTwo
    if operation == "-":
        result = numberOne - numberTwo
    if operation == "*":
        result = numberOne * numberTwo
    if operation == "/":
        result = numberOne / numberTwo
    return result

result = performOperation(numberOne, numberTwo)
print str(result) # will print the result

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.