0

I started coding 2 days back and just for some practice i decided to make a calculator. It keeps giving me errors saying num1 is not defined.

#data collection
def a1(num1, op, num2) :
 num1 = int[input("enter the first number: ")]
 op = input("enter the operation: ") 
 num2 = int[input("enter the second number: ")]


#running the operations
def a2() :
 if (op == "+"):
  num3 = num1 + num2
  print (num3)
 elif (op == "-"):
  num4 = num1 - num2
  print (num4)
 elif (op == "*"):
  num5 = num1 * num2
  print (num5)
 elif (op == "/"):
  num6 = num1 / num2
  print (num6)
 else:
  a1(num1, op, num2)
  a2()
a1(num1, op, num2)
a2()

3 Answers 3

1

Function arguments are positional variables. You need to call the function and pass it the variables in order for it to work.

Variables passed to a function are local, only usable in the function. You want to either change a global variable or return from that function.

What your code is doing is passing unassigned variable names num1, op, num2 to a function.

Read more here: http://www.tutorialspoint.com/python/python_functions.htm

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a way to fix up your existing code:

#data collection
def a1():
    num1 = int(input("enter the first number: "))
    op = input("enter the operation: ") 
    num2 = int(input("enter the second number: "))
    return num1, op, num2

#running the operations
def a2(num1, op, num2):
    if (op == "+"):
        num3 = num1 + num2
        print(num3)
    elif (op == "-"):
        num4 = num1 - num2
        print(num4)
    elif (op == "*"):
        num5 = num1 * num2
        print (num5)
    elif (op == "/"):
        num6 = num1 / num2
        print(num6)
    else:
        num1, op, num2 = a1()
        a2(num1, op, num2)

num1, op, num2 = a1()
a2(num1, op, num2)

The changes I made:

  1. Make a1 not take any parameters but instead return three values.
  2. Make callers of a1 capture the returned values into local variables.
  3. Make a2 accept three parameters.
  4. Change int[...] to int(...).
  5. Fix up some indentation and spaces to conform with typical Python style.

Comments

0

The last two lines:

a1(num1, op, num2)
a2()

are the "main" body of your program. Before that are two function definitions. When you invoke a1, what is the value of num1? Indeed, what is its type? Answer: it's a name with no value associated with it. That's why the Python interpreter complains.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.