Jordan Tyner
Jordan Tyner

Reputation: 11

Python Calculator Programming Errors

def add(x,y):

  y = int( input("Enter First number "))
  x = int( input("Enter Second number "))
  answer = x + y
  print (answer)

def subtract(x,y):

  answer = x - y
  print (answer)
  y = int ( input("Enter First number "))
  x = int ( input("Enter Second number "))


operation = input("Subtract or Add ")

if operation == "add":

  add(x,y)

else:

  subtract(x,y)

I keep getting an error saying variables x and y aren't being used. Please help. I have been stuck on this for a while now.

Upvotes: 1

Views: 71

Answers (3)

FingerLiu
FingerLiu

Reputation: 123

Your code has many problems and it is really confusing.

  1. as ppperry commented, indentation .When writing python, you should use exact 4 space as indentation.

  2. you did not realize the difference between input and raw_input. If you are using python2, and your input is not a number, input while try to eval your input. written in python doc. If you are using python3, you do not need to worry about this because in python3 there is no more raw_input, and input equals old raw_input. This was asked here

  3. follow enpenax's answer. you should first define x and y before you call them.

Upvotes: 0

Ricardo Cid
Ricardo Cid

Reputation: 239

You have problems with your scope. You can't call x or y before calling the function as those variables are declared inside the function. Do it once at a time. First you ask what function. Then once inside the function you ask for x and y

def add():

  x = int( input("Enter First number "))
  y = int( input("Enter Second number "))
  answer = x + y
  print (answer)

def subtract():

  x = int ( input("Enter First number "))
  y = int ( input("Enter Second number "))
  answer = x - y
  print (answer)

operation = input("subtract or add ")

if operation == "add":
  add()
else:
  subtract()

Upvotes: 2

enpenax
enpenax

Reputation: 1562

welcome to Stack Overflow and welcome to Python.

As you might know, in Python indents are really important, as they define which code belongs into which block.

Looking at your request, I must assume that this is a reflection of your code. So I think if you go with the following indentation, it might do what you want:

def add(x,y):
    answer = x + y
    return answer  # Please notice how i use RETURN to return a value from the function call

def subtract(x,y):
    answer = x - y
    return answer

y = int ( input("Enter First number "))
x = int ( input("Enter Second number "))

operation = input("Subtract or Add ")

result = None
if operation == "add":
    result = add(x,y)  # Please notice how I store what the function returns!
else:
    result = subtract(x,y)

if (result != None):
    print result
else:
    print "There is no result!"

Please read the comments and ask if you have any more questions.

Maybe you want to consider an elaborate introduction to Python

Upvotes: 1

Related Questions