I have been the getting results:
Name: Hemingway, Ernest
Name: Madonna,
Name: , Voltaire
Name: ,
It seems as though the code is skipping all of my if and elif statements, I'm new to this so any help would be appreciated. Any explanation to my mistakes would be really beneficial.
def format_name(first_name, last_name):
# code goes here
string = ("Name: " last_name ", " first_name)
if first_name==0 and last_name==1:
print ("Name: " last_name)
elif first_name==1 and last_name==0:
print ("Name: " first_name)
elif first_name==0 and last_name==0:
print ("")
else:
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
''''
CodePudding user response:
def format_name(first_name, last_name):
out = last_name ", " first_name
out = out.strip(", ")
if not out:
return ''
return "Name: " out
CodePudding user response:
You can try this:
def format_name(first_name, last_name):
if last_name: # if last isn't ""
if first_name: # if first isn't ""
return f"Name: {last_name}, {first_name}"
return f"Name: {last_name}"
return f"Name: {first_name}" if first else ""
Output
Name: Hemingway, Ernest
Name: Madonna
Name: Voltaire
CodePudding user response:
You can filter a list for false-y type values and join the results. Then you can return a conditional.
def format_name(first_name, last_name):
name = ", ".join(filter(None, [last_name, first_name]))
return f"Name: {name}" if name else ""
With assignment operator this can be a oneliner:
def format_name(first_name, last_name):
return f"Name: {n}" if (n := ", ".join(filter(None, [last_name, first_name]))) else ""