0

Can someone give me some hints or ideas as to why this:

def fishstore(fish, price):
  total = "Your", fish, "costs", price, "$"
  return total
print (fishstore("sardines", 5))

shows this:

('Your', 'sardines', 'costs', 5, '$')

instead of this:

Your sardines costs 5 $

2 Answers 2

1

You are returning a tuple, and that's what is being printed. Just because you return multiple items separate by commas does not mean print() will see those as separate arguments. Otherwise, how would you print a tuple as a tuple?

If you wanted to print the contents of the tuple as separate arguments, use the *argument call syntax:

print(*fishstore("sardines", 5))

The *argument syntax makes it explicit you want to unpack all the values into separate items for print() to process.

The function isn't all that useful, really. It might be more useful to use string formatting to put the item and price together into a single string to print:

def fishstore(fish, price):
    total = "Your {} costs {}$".format(fish, price)
    return total

at which point print(fishstore("sardines", 5)) will work just fine.

If you are using Python 3.6 (or newer), you can use the f'....' formated string literals syntax too:

def fishstore(fish, price):
    total = f"Your {fish} costs {price}$"
    return total
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for helping! I just have one more question: what do you mean by "the argument call syntax"?thank you!! I'm just beginning with python 3, so sorry if I ask stupid questions.
@MacKenzieRichards: Adding (...) after a name is called a call. Part of that syntax is the ability to specify that an object should not be treated as a single argument to the call, but as a sequence of separate arguments.
@MacKenzieRichards: so print(1, 2, 3) can also be expressed as args = [1, 2, 3], and print(*args). Using *args in the print call tells Python to take all the elements contained in args and use those as separate arguments instead.
Ohhh! Thank you, I think I understand now.
1

You can just concat the string by coding total = "Your " + fish + "costs " + price +"$" in replacement. I'm not too positive why it outputs it in a list like that, but the rest of the code looks correct. You could also just do print ("Your %s cost %d $", fish, price).

In Python, commas don't concat. If you wanted it to be stored in a list, you could also use the .join() function as others have commented.

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.