1

This is my script:

fruit  = "apple"
phrase = "I like eating " + fruit + "s."

def say_fruit(fruit):
    print phrase

say_fruit('orange')

I'm trying to get say_fruit to use the string given inside the phrase variable, which actually uses the variable already assigned before to it (apple). How can I achieve this?

3 Answers 3

3

In your code, phrase is bound to a string when the module loads and is never changed. You need to be dynamic, like this:

def phrase(fruit):
    return "I like eating " + fruit + "s."

def say_fruit(fruit):
    print phrase(fruit)

Globals are just a bad idea that will haunt you in the future. Resist the temptation to use them.

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

3 Comments

Running that gave me <function phrase at 0x0000000001DA8518>. What's this?
No it does not. Try again, but make sure you copy/paste the code from the question.
You forgot to add () at the end of your function.
0

So what you want is this, right?

>>> say_fruit('orange')
I like eating oranges.
>>> say_fruit('apples')
I like eating apples.

If so, move the definition of phrase into the function. The end result should be something like:

def say_fruit(fruit):
    phrase = "I like eating " + fruit + "s."
    print phrase

say_fruit('orange')

Comments

0

When you run this line of code

phrase = "I like eating " + fruit + "s."

Python automatically substitutes 'apple' for fruit and phrase becomes " I like eating apples.".

I prefer using .format() to do this, as it preserves readability:

fruit  = "apple"
phrase = "I like eating {fruit}s."

def say_fruit(fruit):
    print phrase.format(fruit=fruit)

say_fruit('orange')

.format() substitutes {var} with the contents of var when called.

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.