Reusable blocks of logic
print(), len(), type() are all built-in functions. Now you'll write your own.def greet(name):
print(f"Hello, {name}!")
greet("Ada") # Hello, Ada!
greet("Grace") # Hello, Grace!def add(a, b): # a and b are parameters
return a + b
result = add(3, 5) # 3 and 5 are arguments
print(result) # 8return vs print — the #1 beginner mistake. print() displays text but produces None. return sends a value back to the caller so you can use it. If you write print(x) instead of return x, your function "works" visually but you can't do anything with the result.# WRONG — prints but returns None
def bad_add(a, b):
print(a + b)
x = bad_add(3, 5) # Prints "8" but...
print(x) # None! Can't use it.
# RIGHT — returns the value
def good_add(a, b):
return a + b
y = good_add(3, 5)
print(y * 2) # 16 — now you can use it!def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (defaults to squared)
print(power(5, 3)) # 125 (cubed)def make_message():
msg = "Hello from inside!" # Local variable
return msg
result = make_message()
print(result) # Works fine
# print(msg) # NameError! msg doesn't exist out heredef is_even(n):
return n % 2 == 0
def filter_evens(numbers):
return [n for n in numbers if is_even(n)]
print(filter_evens([1, 2, 3, 4, 5, 6]))
# [2, 4, 6]Write two functions: 1. `celsius_to_fahrenheit(celsius)` that **returns** the Fahrenheit value (formula: C × 9/5 + 32) 2. `classify_temp(f)` that **returns** a label: "cold", "cool", "warm", "hot", or "boiling" Then loop through a few temperatures and print the results.
loading editor...
Ask about Functions
◇
Hey! I'm your AI tutor.
Ask me anything about this lesson, or paste code you're stuck on.
AI tutor is a premium feature