0

I am stuck on def functions. Can someone help please?

Hi, I am following along in the “Python Crash Course” book and I am at the part where you are defining functions. It was making sense up until now. The author defines a function then puts the parameters into a variable. Once he returns the variable, he then stores the function into a variable. I don’t understand why. I have the code below. Can you explain this step by step in a way that will make sense to a 6 yr old? Lol need black and white https://code.sololearn.com/ctnxQBmzWjDI/?ref=app

12th Dec 2019, 11:15 PM
James Downing
James Downing  - avatar
5 Antworten
+ 2
Okay, maybe I understood what confuses you. You think, that the function is executed right where it's written, right? That is not the case. A function is a subcode that you define to use it *later*. If you just define your function and run the code, nothing will happen. Only when you actually *call* the function, it will start to do its work. And as soon as it's finished, it will forget everything inside. And when you call it again, it will start fresh. So the line that looks strange to you, is the line where stuff actually happens. As soon as you call the function, it will be executed. And then it will return its return value right to the point where it was called. The function will be gone. x = f() Puts the vessel x in place, so that the return value will not go to waste.
13th Dec 2019, 7:28 PM
HonFu
HonFu - avatar
+ 1
It's about this line, right? musician = get_formatted_name('jimi', 'hendrix') It isn't the function that is stored in the variable, it is the return value. See this: x = 1+1 First 1+1 are added, and then 2, the result, is stored in x. Now let's say we have a function f that returns whatever. x = f() Now again, first the function is executed, and the result (its return value) is stored in x.
12th Dec 2019, 11:38 PM
HonFu
HonFu - avatar
+ 1
If you have hundreds of lines of code with dozens of references to jimi hendrix, you would have to do "get_formatted_name('jimi', 'hendrix')" everywhere in you code...then... if you decided to change jimi hendrix' to some other name...you have to do dozens of amendments....but assigning it to a variable...you only need to change (the name) it once.
12th Dec 2019, 11:42 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Your main program has no access to what happens in the function. And after the function ran, the variables will be deleted. So if you want to have them in your main program, you have to store them somewhere.
13th Dec 2019, 7:18 PM
HonFu
HonFu - avatar
0
yeah its the musician line. why not run it as: get_formatted_name(“x”,”y”) ? since paramaters have veen set within the function i can use any name I want, so why take an extra step and store it inside of musician?
13th Dec 2019, 7:05 PM
James Downing
James Downing  - avatar