CodingNic

Functions and Reusability

Return Values

Functions and Reusability 22 min read

Return Values

Return Values

Sometimes a function should do more than print something.

Sometimes we want a function to give a result back to us.

Python uses the return keyword for this.

What Is Return?

return sends a value out of a function.

That value can be stored in a variable, printed, or used later.

Why Return Is Useful

With return, a function can:

  • Calculate an answer
  • Send data back
  • Be reused in bigger programs
  • Work with other code

These are not the same.

Using Print

python
def add():
    print(2 + 3)

add()

Output

text
5

This shows the answer on the screen.

Using Return

python
def add():
    return 2 + 3

result = add()
print(result)

Output

text
5

This gives the answer back so we can store it.

Another Example

python
def greet(name):
    return "Hello " + name

message = greet("Sara")
print(message)

Output

text
Hello Sara

Return Stops the Function

When Python reaches return, the function ends.

python
def test():
    return "Done"
    print("This will not run")

print(test())

Output

text
Done

Using Return in Math

python
def multiply(a, b):
    return a * b

answer = multiply(4, 5)
print(answer)

Output

text
20

Code Along

python
def square(number):
    return number * number

print(square(6))

Output

text
36

Mini Challenge

Build an add function.

Steps:

  • Create a function called add
  • Give it two parameters
  • Return the total
  • Call the function with 3 and 7
  • Print the result

Expected output:

text
10

Real World Use Case

Programs use return to calculate totals, check results, send data, and build reusable features.

Quiz

  1. What does return do?
  2. Can a returned value be stored in a variable?
  3. Does the function continue after return?
  4. What is the difference between print and return?

Assignment

Create a function called subtract that returns the answer of two numbers. Print the result.

Summary

You learned that return sends a value out of a function so it can be used, stored, or printed later.