Hi,
I’m all new to programming and didn’t understand the explanation/answer at the top either.
But I do think I understand it now, after reading trough the comments.
A function will always return a value. As a programmer you have to define which value will be return
ed by the function. If you don’t define this, the function will automatically return ‘None’
def more_complicated(n):
"""Returns the square of a number and adds 2 to that number."""
squared = n ** 2
complication = squared + 2
print more_complicated(10)
In the above example the function will return ‘None’ , because it doesn’t know which step of the calculation to return
. I didn’t tell him!
Does it have to return
squared or does it have to return the calculation after that? The programmer decides, not the function.
def more_complicated(n):
"""Returns the square of a number and adds 2 to that number."""
squared = n ** 2
complication = squared + 2
return complication
print more_complicated(10)
Adding return
complication will make the function return 102. And for whatever reason I, as a programmer, could have decided to return
squared and the function would have returned 100.
def more_complicated(n):
"""Returns the square of a number and adds 2 to that number."""
squared = n ** 2
complication = squared + 2
print complication
more_complicated(10)
This piece of code will print 102. How is that possible? Because the code doesn’t actaully call the answer of the function. The print statement is inside of the function.
Adding print more_complicated(10) further along in your code (outside of the function), will return ‘None’ because inside of the function, nothing was returned. (and it will also print 102 again, because the print statement is still inside of the function.)