Last updated
Python Functions
Definition: A function is a named, reusable block of code. You define it once, then "call" it whenever you need it — which keeps code organised and avoids repetition.
Example 1 — define and call
def greet():
print("Hello!")
greet() # call it
greet() # call again
Use def, a name, brackets, and a colon. The indented lines are the function body.
Example 2 — parameters (inputs)
def greet(name):
print("Hello, " + name)
greet("Sam")
greet("Alex")
Example 3 — returning a value
return sends a result back so you can use it elsewhere:
def add(a, b):
return a + b
result = add(3, 4)
print(result)
print(add(10, 20))
Example 4 — default values
def greet(name="friend"):
print("Hi, " + name)
greet() # Hi, friend
greet("Sam") # Hi, Sam
Example 5 — a small useful function
def is_even(n):
return n % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
💡 Tip: a good function does one clear job and has a name that says what it does, like calculate_total or send_email.
Try it Yourself
Output
Ad · responsive