Hello I'm a beginner in python. I use python 3 and have a problem with my code. I did the exact same but with addition and subtraction and it worked fine but when I do it with division and multiplication I get a error. Here is the code:
import math
division = 'division'
multiplication = 'multiplication'
class calculator:
math = input('Enter division or multiplication: ')
if math == division:
x = float(input('First number: '))
y = float(input('Second number: '))
def division(x,y):
div = x / y
print(div)
division(x / y)
elif math == multiplication:
x = int(input('First number: '))
y = int(input('Second number: '))
def multiplication(x,y):
mult = x * y
print(mult)
multiplication(x * y)
else:
print('Invalid input!')
and here is the error i get:
Traceback (most recent call last):
File "/Users/linusekman/Desktop/test1.py", line 6, in <module>
class calculator:
File "/Users/linusekman/Desktop/test1.py", line 16, in calculator
division(x / y)
TypeError: division() missing 1 required positional argument: 'y'
What can the problem be?
-
3Why do you even have a class statement here?user2357112– user23571122017年05月18日 23:03:33 +00:00Commented May 18, 2017 at 23:03
3 Answers 3
division(x / y) and multiplication(x * y) needs to be changed to division(x , y) and multiplication(x , y), or else you're passing the solution of x/y and x*y to the function, not the two values itself.
Side note: you shouldn't import math if you're not doing to use it, and that you already overrode variable math in your class's slope, math = input('Enter division or multiplication: ').
Another side note: the class structure isn't necessary for what you're doing, if you wanted to reuse that piece of code, change the class to a function.
Comments
You want division(x, y) instead of division(x / y). (Same thing for multiplication.)
Comments
Let's look at your example (^.^)
if math == division:
x = float(input('First number: '))
y = float(input('Second number: '))
def division(x,y):
div = x / y
print(div)
division(x / y) <-(pay attention to this line!)
When you create a function called def division (x,y), you are stating that this function will accept two variables.
You go on to say that this function will print the quotient of when you divide x by y ( div = x/y and print(div)).
When you want to call your divide function, you have to pass it two variables upon which it can perform the task you assigned it to do. You don't pass it x/y, because 1) it requires two variables 2) the function will do that with the two variables passed.