+ 1

I need help in Python.

How do functions work? Specifically that return statement? I never understood it, even from the python course in Sololearn, i even tried youtube but it also didn’t work. Plz answer ASAP.

24th Feb 2024, 9:13 AM
Abdo Kawji 🇸🇾
Abdo Kawji 🇸🇾 - avatar
6 odpowiedzi
+ 6
Abdo Kawji , here is a a short and simple code that demonstrates how to use the return statement from a function. we pass 2 values to a function, calculate the average of them and return the result back to the caller: https://sololearn.com/compiler-playground/c8w79FUr1j7u/?ref=app
24th Feb 2024, 9:25 PM
Lothar
Lothar - avatar
+ 4
say you want to add numbers. you can write: x = 1 + 2 when you write: print(x) you can see what's stored in x, which is 3. Variables store values, functions stores procedures. You can store the process in a function: def addnumbers(a, b): return a + b this runs a+ b and gives the result to whatever receives the function's return value. if you write: x = addnumbers(1,2) a=1 and b=2. a+ b becomes 1+2 and 3 is 'returned' to x, so it is the same as writing x = 1 + 2 so x is now equals to 3. if you write: print(addnumbers(1,2)) 3 is 'returned' to print()as an argument so it is basically print(3) and 3 is printed out.
24th Feb 2024, 10:36 AM
Bob_Li
Bob_Li - avatar
+ 2
Here is a little code I made about describing the return keyword. Since "return" works inside a function, it should answer to your question as well. https://sololearn.com/compiler-playground/cVF03G3wAXBt/?ref=app
24th Feb 2024, 10:43 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 2
the average value is stored in result. average_temp is the name of the function that stores the calculation.
25th Feb 2024, 6:14 AM
Bob_Li
Bob_Li - avatar
+ 1
External code pushes arguments onto the stack before calling the function. Then control is transferred to the address that corresponds to the entry point into the function. At the entry point, values are popped from the stack before the statement block is executed. The return statement pushes the return value onto the stack before exiting the function. Control is then transferred to the calling external code. At the exit point of the function, the values are popped from the stack and then become the result of evaluating the expression to the right of the assignment.
26th Feb 2024, 8:26 AM
Artyom Nazarov
0
Lothar do you mean we store the returned value in average_temp?
25th Feb 2024, 4:52 AM
Abdo Kawji 🇸🇾
Abdo Kawji 🇸🇾 - avatar