MacKenzie Richards
MacKenzie Richards

Reputation: 19

Why is my return function not working the way I want it to? (Python 3)

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 $

Upvotes: 0

Views: 93

Answers (2)

davleop
davleop

Reputation: 11

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.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124548

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

Upvotes: 1

Related Questions