Ask your own question, for FREE!
MIT 6.189 A Gentle Introduction to Programming Using Python (OCW) 12 Online
OpenStudy (anonymous):

Just getting started with MIt 6.189. I am not understanding how Problem 10 Exam 1 returns 0,5. Can someone assist. def f(a): a=a+5 return a b=0 f(b) print b, ",", b = f(b) print b

OpenStudy (rsmith6559):

The first call to f(b) doesn't assign the return value, the second does.

OpenStudy (e.mccormick):

To expand on what rsmith6559 said: f(b) is a call to the function f with the value of b. The function does the internal math in a separate namespace. Nothing has actually changed in the original b. Then f returns the input + 5, but f(b) is on a line by itself so that goes nowhere. Sort of like if a person tosses a ball and nobody is there to catch it then it is not caught. The ball falls to the ground and rolls away. b = f(b) starts out the same way. A copy of b is put into f in a separate namespace. f does its work and tosses back 5. This time there is b= out there so b catches the address that points to 5. To do this it had to drop the address that pointed to 0. Now b is a representation of 5 and no longer 0. Because the print statements happen after each of these steps, you get the unchanged b then the changed b. All of this is wonderfully summarized by rsmith6559, but if you still wanted more: there it is!

OpenStudy (dan815):

def f(a): a=a+5 return a you got a function f function f takes an input and adds 5 to it, and returns that value... f(b)= b+5 f(0)=0+5=5 then its printing, what you input and the new value with this command print b, ",", <---- right now b is still 0 b = f(b) <----- now b became b=0+5=5 print b <---- this is added to the top print command because there is a comma at the end of it

OpenStudy (anonymous):

def f(a): a=a+5 return a b=0 f(b) # nothing print b, ",", # print 0 b = f(b) # b = f(0) = "a = 0 + 5" = "a = 5" = 5 print b #print 5

OpenStudy (anonymous):

when f(b) is called the first time, the function returns 5 but it doesn't change the value of b. So it remains 0. but the the next time you assign b=f(b) as the function returns 5 which is then assigned to the variable b. Hence this time it prints 5. so the output is 0,5

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!