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))
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
JmanK
  • 11
  • 3
  • 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, – MooingRawr Apr 03 '17 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. – Josh Apr 03 '17 at 20:58

2 Answers2

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)
Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
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
lordingtar
  • 1,042
  • 2
  • 12
  • 29