3. Return
return ends the function and sends a value back to the caller. The call expression then evaluates to that value:
return expressioncomputes the expression and gives the result back.- Code after
returnin the same branch does not run. - A function without
returngives backNone. print()shows text in the console;returngives a value to the caller. They are not the same thing.
Return a value
Define double(n) that returns n * 2. Do not print inside the function. Call it inside print() with the argument 5.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Store the returned value
Define square(n) that returns n * n. Store the result of square(3) in a variable named result, then print result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A function without return gives None
Define say_hi() that prints Hi and has no return. Then print the result of calling say_hi().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use the returned value in an expression
Define double(n) that returns n * 2. Print double(3) + 1 directly, without storing the result first.
Print exactly:
Create a free account to save your progress and unlock chapter 2.