[Tutor] Why do I get "None"?
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jan 26 04:23:43 EST 2021
On 26/01/2021 04:49, H K wrote:
> def greeting_2(name):
> print("Hello " + name)
Every time you define a function without an explicit return
statement Python implicitly returns None.
> example = greeting_2("Christine")
The line above prints he greeting inside the function
> print(example)
This line prints the return value which is None.
> This gives the value:
> Hello Christine
>From inside the function
> None
>From your print(example)
This confusion could have been avoided by *returning*
the greeting as a string rather than printing it inside
the function:
def greeting_3(name):
return "Hello" + name
example = greeting_3("Christine")
print(example)
This is considered better practice than embedding
print statements inside functions that create data.
Generate the data inside the function and return it.
Then print the result of the function separately.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list