0

I am quite new to python programming and I need some help solving a problem with the function below :

def format_name(first_name, last_name):
    string = first_name, last_name

    if string == first_name and last_name:
      return ('Name: ' + last_name + ', ' + first_name)

    elif string == '' and last_name:
      return ('Name: ' + last_name)

    elif string == first_name and '':
      return ('Name: ' + first_name)

    else:
      return ''

    return string 

The desired outputs :

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.

Can anyone point out my mistake ?

4
  • 1
    Return a tuple of 2! Commented May 10, 2020 at 1:43
  • None of your conditions will ever match. You are comparing a tuple with strings, Commented May 10, 2020 at 1:46
  • Printing is not the same thing as returning. Saying that print(format_name("", "Madonna"))` 'Should return the string "Name: Madonna"' doesn't make a lot of sense. The word "return" there should be replaced by "print". In some ways I am being picky, but confusing print and return is a common mistake of first-time programmers learning Python. Commented May 10, 2020 at 1:46
  • And your return string can not be reached. Commented May 10, 2020 at 1:50

1 Answer 1

1

In your code you are compering a string with a tuple which is always False string = first_name, last_name string value will be a tuple like this ('fname', 'lname') and of course it's not equals to any string.

If you want to return multiple values as a returning value of the function you can do something like this:

def func():
  return "first string", "second string"

This will return the following tuple ("first string", "second string")

You can receive it as the following:

first, second = func()

first will be "first string" as a string and second will be "second string" as a string too in this case

You can check after that according your program logic.

Hope that somehow helped

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.