Return Statement
Imagine you ask a friend to go to the store and buy a chocolate bar. They go to the store (the function), buy the chocolate, and then they return to you and give you the chocolate. In Python, the return statement is how a function gives a result back to you instead of just keeping it!
What is the Return Statement?
The return statement is used to send a value from a function back to the main part of your program.
-
The Exit Door: When Python hits a return statement, the function stops immediately.
-
Storage: Unlike
print(), which just shows text on the screen, return lets you save the answer in a variable to use later. -
Versatile: You can return numbers, words, or even lists!
Real-World Return Scenarios
-
Grading System: A function calculates your score and returns "Pass" or "Fail."
-
Shopping App: A function adds up the items in your cart and returns the total bill amount.
-
Login System: When you enter a password, a function returns
Trueif it's correct. -
Calculator: You send numbers to a function, and it returns the final answer.
How it Looks (Syntax & Examples)
The Pattern:
def function_name():
return value
Example 1: The Math Result
def add(a, b):
return a + b
# We save the result of the function in a variable
result = add(5, 3)
print(result)
Output: 8
Example 2: Sending a Message Back
def message():
return "Welcome"
print(message())
Output: Welcome
Summary:
-
Instant Stop: Nothing written after the return line inside a function will ever run.
-
Smart Programs: Using return makes your functions much more powerful because they can "talk" to the rest of your code.
-
Calculations: Always use return when your function is doing math or making a decision.