loading...
CodeNewbie

April 18 — Daily CodeNewbie Check-in Thread

codenewbiestaff profile image CodeNewbie Staff ・1 min read

You are encouraged to use this daily thread to:

  • Ask for help (all questions encouraged)
  • Explore topics you’re curious about
  • Share something you’ve written or read
  • Celebrate your wins
  • Stay accountable to your goals
  • Support your fellow programmers

Happy Coding!


Interested in joining the twice-weekly live #CodeNewbie Twitter chats? You can find us on Twitter each Wednesday at 9pm ET (1am GMT on Thursday) and Sunday at 2pm ET (6pm GMT)!

Discussion

pic
Editor guide
Collapse
jankosutnik profile image
Jan Kosutnik

There is an interesting thread about launching your own little product, OP ( Zeno Rocha ) tqlks about how he approached it and so on...

twitter.com/zenorocha/status/12493...

Collapse
scanlonms89 profile image
Rory

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

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!