2

Working through a Python tutorial. I created a simple script (myFirstFunction) that does not perform whats expected. I expected a line of output that is just two variables multiplied together:

apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")

def myFirstFunction(apples, oranges):
    total_fruit = apples * oranges
    print total_fruit

The script does ask for the inputs as expected, but does not print out the results?

myName-MacBook:pythonhard me$ python ex19b.py
How many apples do you have?2
How many oranges do you have?2
myNames-MacBook:pythonhard me$ 

Why does it not print out 4?

2
  • 2
    You are never calling the function... Commented Dec 8, 2013 at 20:06
  • 2
    Because you are not calling myFirstFunction anywhere. Commented Dec 8, 2013 at 20:06

3 Answers 3

6

There are two issues here:

  1. You never call myFirstFunction. This can be done by placing this at the end of your script:

    myFirstFunction(apples, oranges)
    
  2. raw_input always returns a string object. So, the inputs need to be converted into integers before you multiply them inside myFirstFunction. You can do this by placing them in int:

    apples = int(raw_input("How many apples do you have?"))
    oranges = int(raw_input("How many oranges do you have?"))
    

Here is a fixed version of your script:

apples = int(raw_input("How many apples do you have?"))
oranges = int(raw_input("How many oranges do you have?"))

def myFirstFunction(apples, oranges):
    total_fruit = apples * oranges
    print total_fruit

myFirstFunction(apples, oranges)

Demo:

How many apples do you have?2
How many oranges do you have?2
4
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! Thank you. I got it now, accepting when the time limit comes of
2

You need to a) call the function & b) convert the input to integers because the result of a raw_input is a string.

def myFirstFunction(apples, oranges):
    total_fruit = int(apples) * int(oranges)
    print total_fruit

apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")

myFirstFunction(apples, oranges)

Comments

2

You should have

return total_fruit

in function, then call myFirstFunction and print result:

def myFirstFunction(apples, oranges):
   total_fruit = apples * oranges
   return total_fruit

apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")

print myFirstFunction(apples, oranges)

or just call myFirstFunction (when no return):

myFirstFunction(apples, oranges)

1 Comment

Thanks for informing me about "return".

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.