Defining and Using Functions

Learn how to define and use functions in Python, including function syntax, calling functions, and the pass statement.

Ali Berro

By Ali Berro

5 min read Section 1
From: Python Fundamentals: From Zero to Hero

Defining and Using Functions

A function is a block of organized, reusable code that is used to perform a specific task. A function should only perform a single, related action.

Python has multiple built-in functions, such as print(), len(), input(), etc. We can also define our own functions to perform specific tasks.

Function Definition Syntax

To define a function in Python, we use the def keyword followed by the function name and parentheses:

function-definition.py
def functionName(parameter1, parameter2, ...):
# We have created a new scope
# We put statements here
pass

The function definition consists of:

  1. The def keyword
  2. The function name (following the same naming rules as variables)
  3. Parentheses () that may contain parameters
  4. A colon : to indicate the start of the function body
  5. The function body (indented code block) - this creates a new scope

Note

By convention, function names use lowercase letters with underscores separating words (snake_case), e.g., calculate_total, get_user_input.

Calling Functions

To execute a function, we call it by writing its name followed by parentheses:

calling-functions.py
def say_hello():
print("Hello!")
say_hello() # Function call
say_hello() # Can be called multiple times

Functions with Parameters

Functions can accept parameters (inputs) to make them more flexible. We can also give functions some values. These values are called arguments of a function.

function-with-parameters.py
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!

A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.

We can give a function your name, and it can greet you!

Functions with Return Values

All functions in Python return a value. This is done using the return keyword. If not specified, a function will return None.

function-with-return.py
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
no-return.py
def greet(name):
print(f"Hello, {name}!")
result = greet("Alice")
print(result) # None

Multiple Return Values

Python functions can return multiple values using tuples:

multiple-returns.py
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(name) # Alice
print(age) # 25

This is actually returning a tuple, which is then unpacked into multiple variables.

The pass Statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program does no action:

pass-statement.py
def future_function():
pass # Placeholder - function does nothing for now
def calculate():
# TODO: Implement calculation logic
pass

Function Body

The function body contains the code that executes when the function is called. It must be indented:

function-body.py
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 3)
print(result) # 15

Example: Complete Function

complete-function-example.py
def calculate_discount(price, discount_percent):
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price
original_price = 100
discount = 20
final = calculate_discount(original_price, discount)
print(f"Original: ${original_price}, Final: ${final}")

Exercises

Exercise 1: Function Definition

Write a function called greet_user that takes a name as a parameter and prints “Hello, [name]!”.

Answer:
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice")

Exercise 2: Function with Return Value

Write a function called multiply that takes two numbers as parameters and returns their product.

Multiply Function

Checks: 0 times
Answer:
def multiply(a, b):
return a * b
a = int(input())
b = int(input())
result = multiply(a, b)
print(result)

Exercise 3: Function Returning None

What will be printed by the following code?

def display_message():
print("Hello World")
result = display_message()
print(result)
Answer:
Hello World
None

The function prints “Hello World” but returns None since there’s no return statement.

Exercise 4: Multiple Return Values

Write a function called get_name_age that reads a name and age from input, then returns them. Call the function and unpack the values into two variables, then print them.

Multiple Return Values

Checks: 0 times
Answer:
def get_name_age():
name = input()
age = int(input())
return name, age
name, age = get_name_age()
print(f"Name: {name}, Age: {age}")

Exercise 5: Pass Statement

Write a function stub called calculate_area that uses the pass statement. The function should accept length and width as parameters.

Answer:
def calculate_area(length, width):
pass # TODO: Implement area calculation

Course Progress

Section 33 of 61

Back to Course