Functions help organize code by grouping related tasks. They make programs easier to read, reuse, and fix.
What is a function?
A function is a block of code that performs a specific task. You define it once and call it whenever needed.
Define a simple function with the def keyword:
def greet():
print("Hello!")
Call the function by its name followed by parentheses:
greet() # Prints: Hello!
The indented block after the colon is the function body.
Adding parameters
Parameters let you pass values into a function.
def greet(name):
print(f"Hello, {name}!")
Here, name is a parameter.
Call it with an argument (the actual value):
greet("Alex") # Prints: Hello, Alex!
greet("Sam") # Prints: Hello, Sam!
You can have multiple parameters:
def add(a, b):
print(a + b)
add(5, 3) # Prints: 8
Parameters are the names inside the parentheses during definition.
Arguments are the values you pass when calling the function.
Using return
So far, functions only print things. Use return to send a value back to the caller.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Prints: 8
The function stops at return and sends the value back. You can store or use it later.
Common mistake: print vs return
Many beginners confuse printing with returning.
def get_square(n):
print(n * n) # Only prints
value = get_square(4) # Prints 16
print(value) # Prints: None
Fix it with return:
def get_square(n):
return n * n
value = get_square(4)
print(value) # Prints: 16
print shows output on the screen.
return gives a value back for further use.
Simple examples
Calculate area of a rectangle:
def rectangle_area(length, width):
return length * width
print(rectangle_area(10, 5)) # 50
Check if a number is even:
def is_even(number):
return number % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
Important notes
- Function names should be lowercase with underscores (snake_case).
- The colon
:and indentation are required. - Use
returnwhen you need the result elsewhere. - A function can have zero, one, or many parameters.
Quick summary
- Define functions with
deffollowed by a name and parentheses. - Parameters accept input values.
-
returnsends a value back to the caller. - Use functions to keep code clean and reusable.
Practice by writing small functions for common tasks. Functions are a key building block in Python programs.
Top comments (0)