A function is a reusable block of code with a name. You write it once, then call it whenever you need it — no copy-pasting. You've already used functions: print() and len() are built-in ones!
✍️ Defining your own
Use the def keyword. Don't forget the colon and indentation:
def greet():
print("Hello there!")
print("Welcome to Python!")
greet() # call it — runs the two prints
greet() # call it again!
📌 Define, then call
Writing def greet(): only creates the function. Nothing happens until you call it with greet().
🎁 Parameters — giving input
A parameter lets you pass information into a function so it can behave differently each time:
Write a function is_even(n) that returnsTrue if n is even, False if odd. Print is_even(8) then is_even(3). Output:
True
False
def is_even(n):
return n % 2 == 0
print(is_even(8))
print(is_even(3))
🎲
Task 5: Free Play — Your Own Function
Creative
Invent a useful function! Ideas: double(n) that returns n×2, shout(word) that returns it in CAPS, or a function that builds a fun greeting. Call it a few times.