+ 2

Whats wrong with my code?

def my_function(): sum=a+b return sum my_function(2,3)

13th Aug 2017, 1:43 AM
Darwin
Darwin - avatar
7 Réponses
+ 2
Your function was defined with no parameters. Inside your function you have two variables called a and b, but the function was defined without them. All you have to do to fix this problem is to add the parameters to your function. Change def my_function(): to def my_function(a, b). I hope this helps!
13th Aug 2017, 1:51 AM
Erik Johanson
Erik Johanson - avatar
+ 2
...and, if it's in CodePlayground you'll need to print/save the results in a variable. Note... "sum" is a reserved work in Python. What you're doing will work, just keep in the back of your mind that Python uses that name too.
13th Aug 2017, 2:16 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
#nothing is wrong, you're just missing a few more steps and may have added some unnecessary steps, there's no perfect answer and it can be written in many different ways. Try this one: def my_function(a,b): a = int(a) b = int(b) result = int(a) + int(b) print(result) my_function(2,3) #If you're going to put values inside the function make sure you add the parameters.
13th Aug 2017, 3:45 AM
Michael
Michael - avatar
+ 1
thanks bro!!!
13th Aug 2017, 2:14 AM
Darwin
Darwin - avatar
+ 1
when I used return the compiler gave no output..but when I used print statement i received the answer .why?
13th Aug 2017, 2:18 AM
Darwin
Darwin - avatar
+ 1
1. it's python, that is interpreter (so it does not compile, it runs stright from source) 2. The interactive console is designed in such way it gives you as much info as it can But for user you need to send it into console. When you call a function in interactive console, it sees that it returned something, that nothing took care of and shows it to you, but in normal programm whan nothing takes what function returned, it will just disappear. So you need to take what the function returned and give it to print, that takes care of showing it to user.
13th Aug 2017, 2:45 AM
Michal Pácal
Michal Pácal - avatar
+ 1
#heck if you want something really short & simple it can also be done this way: def my_function(a,b): return a + b print(my_function(2,3))
13th Aug 2017, 3:54 AM
Michael
Michael - avatar