2

I have what I believe to be an embarrassingly simple problem, but three hours of googling and checking stackoverflow have not helped.

Let's say I have a very simple piece of code:

def secret_formula(started):
  jelly_beans = started*500
  jars = jelly_beans/1000
  crates = jars/100
  return jelly_beans,jars,crates

start_point = 10000

print("We'd have {} beans, {} jars, and {} crates.".format(secret_formula(start_point)))

What happens is I get the "IndexError: tuple index out of range". So I just print the secret_formula function to see what it looks like, and it looks like this:

(5000000, 5000.0, 50.0)

Basically, it is treating the output as one 'thing' (I am still very new, sorry if my language is not correct). My question is, why does it treat it like this and how do I make it pass the three outputs (jelly_beans, jars, and crates) so that it formats the string properly?

Thanks!

1 Answer 1

1

The format function of the string take a variable number of argument. The secret_formula function is returning a tuple. You want to convert that to a list of arguments. This is done using the following syntax:

print("We'd have {} beans, {} jars, and {} crates.".format(*secret_formula(start_point)))

The important par is the * character. It tell that you want to convert the following iterable into a list of argument to pass to the function.

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

1 Comment

Thanks! I tried to use the * but I was putting it in the wrong place so I gave up.

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.