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)!
Latest comments (3)
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("", ""))
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 aprintstatement e.g: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 isfirst_name == ""which is true, so string will be"Name: " + last_namebutlast_nameis an empty string, so you will haveName: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
ifstatement like the one above is to use a guarded statement to return early, maybe something like:That's just one possibility that might make your code a bit more readable and clean :) Good luck!
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...