[Tutor] Python programming question related to Return/Print statement

Richard Damon Richard at Damon-Family.org
Mon Aug 17 10:32:53 EDT 2020


On 8/17/20 8:53 AM, Brenda Ives wrote:
> Good morning,
>
>
>
> While I am still learning python, I've been programming for a very long time.  Some of what the issues with this is logical knowing how computers work.  While we know that "" means you don't print anything computers are literal and they will print a space and a comma when you don't want that to occur.  You need to check for empty values and skip them.  This was actually a good learning lesson for me so I had to try it.  Here is what my attempt arrived at.
>
>
>
> def format_name(first_name, last_name):
>
>     # return "Name: " + first_name + ", " + last_name
>
>     if last_name is '':
>
>         return "Name: " + first_name
>
>     elif first_name is '':
>
>         return "Name: " + last_name
>
>     else:
>
>         return "Name: " + last_name + ", " + first_name
>
>
>
>
>
> 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
>
>
>
> When I ran it, here is the result.
>
>
>
> Name: Hemingway, Ernest
>
> Name: Madonna
>
> Name: Voltaire
>
> Name:
>
>
Note, the test last_name is '' doesn't check that the last_name is some
empty string but is THAT particular empty string. 'is' is not just an
equality check, but an identity check. Python just happens to cache
certain values, so one empty string may end up being used for many of
them, but this is not guaranteed, and particularly, if the empty string
comes out of a

If you want to check for equality of value, use == to make that test.

-- 
Richard Damon



More information about the Tutor mailing list