[Tutor] string formatting (was Re: Help)
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Oct 7 17:33:36 EDT 2020
Always start a new thrad with a new *descriptive* subject line
for new topics. This has nothing to do with your previous
message about divisors.
On 07/10/2020 21:22, Gilbert Makgopa wrote:
> The function below prints "None" in between the output lines. Please assist.
> Here is the results:
>
> Name: Hemingway Ernest
> None
> Name: Madonna
> None
>
> Function:
> def format_name(first_name, last_name):
> # code goes here
> if (first_name != "" and last_name != ""):
> string = print("Name: " + last_name , first_name)
What value does print() return? Try it in the interpreter.
>>> val = print('')
>>> print("Print returned: ", val)
> print(format_name("Ernest", "Hemingway"))
> # Should return the string "Name: Hemingway, Ernest"
Since format_name usually returns the result from print()
you should now know the answer.
In more general terms your function should *return*
the formatted string not print it. You should not have
any print() statements inside your function.
Just generate a string and return that.
Your exterior code can then print the result of
the format function exactly as you attempted to do.
The reason for this approach is because it makes your
function usable in other contexts beside printing in
the console. If you need to generate a web page for
example, or send the data over a network. You can
still use a formatted string, but the print output
would just be lost.
Keep code that displays data separate from the code
that creates the data.
--
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