[Tutor] Help
Cameron Simpson
cs at cskk.id.au
Wed Oct 7 17:26:40 EDT 2020
On 07Oct2020 22:22, Gilbert Makgopa <gmakgopa at gmail.com> wrote:
>The function below prints "None" in between the output lines. Please assist.
That is because your format_name() function is returning None. I suspect
you thing your final:
print(format_name("Ernest", "Hemingway"))
line is printing "Name: Hemmingway Ernest", but it is not. It is printing
"None" because that is what format_name() is returning. Instead, the
"Name: Hemmingway Ernest" output is coming from this code:
if (first_name != "" and last_name != ""):
string = print("Name: " + last_name , first_name)
which itself calls print(), producing the output. For added fun, the
return from print() is None, so string==None. And you return string,
thus None, and then print that.
Change the line to:
string = "Name: " + last_name + " " + first_name
and similarly elsewhere and see what happens. You will also find it
illuminating to put a:
print("string =", string)
just before the "return string" at the bottom of your function. In fact,
do that _before_ making the fix - it will make the situation more clear
to you.
Cheers,
Cameron Simpson <cs at cskk.id.au>
>Here is the results:
>
>Name: Hemingway Ernest
>None
>Name: Madonna
>None
>Name: Voltaire
>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)
> elif (first_name == "" and last_name != ""):
> string = print("Name: " + last_name)
>
> elif (first_name != "" and last_name == ""):
> string = print("Name: " + first_name)
>
> elif (first_name == "" and last_name == ""):
> string = " "
> return string
>
>
>print(format_name("Ernest", "Hemingway"))
># Should return the string "Name: Hemingway, Ernest"
>
>print(format_name("", "Madonna"))
># Should return the string "Name: Madonna"
>
>print(format_name("Voltaire", ""))
># Should return the string "Name: Voltaire"
>
>print(format_name("", ""))
># Should return an empty string
More information about the Tutor
mailing list