DEV Community

Discussion on: April 18 — Daily CodeNewbie Check-in Thread

Collapse
 
scanlonms89 profile image
Rory • Edited

Python question: Could someone help explain why the else statement is returning "Name:" and not an empty string? I'm so close!

*apologies for the large comment. Tried uploading a screenshot but it wouldn't.

def format_name(first_name, last_name):
if first_name and last_name != "":
string = "Name: " + str(last_name) + "," + " " + str(first_name)
elif first_name == "":
string = "Name: " + last_name
elif last_name == "":
string = "Name: " + first_name
else:
string = ""

return string

print(format_name("Ernest", "Hemingway"))
print(format_name("", "Madonna"))
print(format_name("Voltaire", ""))
print(format_name("", ""))

Collapse
 
__mateidavid profile image
Matei David • Edited

Hi Rory,

Your last case (i.e the else) is never reached, an easy way to check your cases in the future would be to add a print statement e.g:

else:
 print("else reached"
 // rest of your code

Now, as to why your code doesn't work, it's quite simple. When you do format_name("","") the first condition in your if block is ignored (since they are both different to empty string). The next condition in the block is first_name == "" which is true, so string will be "Name: " + last_name but last_name is an empty string, so you will have Name: as the result.

Another issue is the first line, which to me should be if first_name != "" and last_name != ""

I'm not a python user, but a good rule of thumb for me when I deal with an if statement like the one above is to use a guarded statement to return early, maybe something like:

def format_name(first_name, last_name):
  if first_name == "" and last_name == "":
     return ""

  formatted_name = "Name:"
  if first_name != "":
    formatted_name += " " + first_name

 if last_name != "":
    formatted_name += " " + last_name

 return formatted_name

// Prints
 print(format_name("Ernest", "Hemingway")) // Name: Ernest Hemingway
print(format_name("", "Madonna")) // Name: Madonna
print(format_name("Voltaire", "")) // Name: Voltaire
print(format_name("", "")) // nothing printed

That's just one possibility that might make your code a bit more readable and clean :) Good luck!