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:
def functionName(parameter1, parameter2, ...): # We have created a new scope # We put statements here passThe function definition consists of:
- The
defkeyword - The function name (following the same naming rules as variables)
- Parentheses
()that may contain parameters - A colon
:to indicate the start of the function body - 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:
def say_hello(): print("Hello!")
say_hello() # Function callsay_hello() # Can be called multiple timesFunctions 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.
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.
def add(a, b): return a + b
result = add(3, 5)print(result) # 8def greet(name): print(f"Hello, {name}!")
result = greet("Alice")print(result) # NoneMultiple Return Values
Python functions can return multiple values using tuples:
def get_name_and_age(): return "Alice", 25
name, age = get_name_and_age()print(name) # Aliceprint(age) # 25This 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:
def future_function(): pass # Placeholder - function does nothing for now
def calculate(): # TODO: Implement calculation logic passFunction Body
The function body contains the code that executes when the function is called. It must be indented:
def calculate_area(length, width): area = length * width return area
result = calculate_area(5, 3)print(result) # 15Example: Complete Function
def calculate_discount(price, discount_percent): discount_amount = price * (discount_percent / 100) final_price = price - discount_amount return final_price
original_price = 100discount = 20final = 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]!”.
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
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)Hello WorldNoneThe 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
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.
def calculate_area(length, width): pass # TODO: Implement area calculation