Python Functions, Packing, and Unpacking Getting Info In and Out of Functions Arguments and Parameters

mohan Abdul
PRO
mohan Abdul
Pro Student 1,453 Points

why isn't the output 7, instead the output is 5.

why isn't the output 7, instead the output 5

2 Answers

Sean T. Unwin
MOD
Sean T. Unwin
Treehouse Moderator 28,639 Points

The variable, num is printed before the addition is done. Essentially, it's passing the initial value of the parameter passed to the function.

Kyle Salisbury
Kyle Salisbury
10,975 Points

Yeah, I understand your confusion, I'm not sure why she taught it like this. She needed to Print the called function, and not just call the function to make things more clear. Hopefully this will help. I'll try to break it down line by line.

def add_two(num):
    print(num) # not important. She was just trying to prove that num equals the value of what ever you passed into it.
    val = num + 2 # important code. what ever number we decide to pass (5 in our case), add two to it and call that variable val.
    return val # This then takes that stored variable value (7 in our case) and saves it in the add_two function ready to be called.

add_two(5) #When you call a function, it does not show it's value it stores. You have to print it if you want to see it.

So when you call a function like she did add_two(5), it doesn't show you the value, it just processes it. The only way to show the value is if you were to print the function like this: print(add_two(5)). This would have done two things. It would first show the number 5, only because we have the code in there that says print(num) and we made num=5. However what we really care about is the value the function created. So the second thing it would have done is show the number 7.

So if we were to delete that print function inside the add_two function, we would have had code that looked like this:

def add_two(num):
    val = num + 2 
    return val 

print(add_two(5))

Output:

7

I hoped this helped.