Kids Coding
Functions that Return
return sends a value back. Call the function. Use the result.
KidsAdvancedFunctions that Return
Give a value back
print shows something. return hands a value to whoever called the function. You can store it and use it.
score()
def score(points):
return sum(points)
total = score([10, 20, 5])
print("Total:", total)print shows a value on the screen; return hands it back so the rest of your code can use it. A function that only prints cannot be added up, saved, or checked later.
Return vs print
| return | ||
|---|---|---|
| You see it | Yes | Only if you print the result |
| You can reuse it | No | Yes — put it in a variable |
Use the result twice
def double(n):
return n * 2
value = double(4)
print(value)
print(value + 1)Real life
A shop calculator: you want the number back, not just to see it.
print shows the total. return hands it to you so you can pay, or save, or add a bag.
Shop total
def total(price, count):
return price * count
pay = total(3, 4)
print("Pay", pay)
print("If I buy one more:", pay + 3)Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Write add(a, b) that returns a + b. Print add(3, 4).
Show solution
def add(a, b):
return a + b
print(add(3, 4))