Python Functions



Table of Contents

  1. What are Python Functions?
  2. Syntax of Python Functions
  3. Creating and Calling a Function
  4. Types of Functions
  5. Default Arguments
  6. Arbitrary Arguments
  7. Keyword Arguments
  8. The Return Statement
  9. Nested Functions
  10. Recursive Functions
  11. Practice Exercises

What are Python Functions?

At its core, a function is a set of code that performs a specific task or action. It enables programmers to break down their code into smaller, reusable blocks, making it easier to read, understand, and maintain. In Python, functions are created using the “def” keyword, followed by the function name and a set of parentheses. Any variables created within the function are known as local variables and are only accessible within the function itself.
Functions are a crucial component of any programming language, including Python. Developers can organize code, make it more readable, and reuse code blocks efficiently.

Syntax of Python Functions

To create a Python function, you need to follow a specific syntax. Here is the basic structure of a function:

def function_name(arguments):    
     # Code block    
        return value

Let’s break down the syntax:

  • The “def” keyword is used to define a function.
  • “function_name” is the name of the function, which should be descriptive and indicative of its purpose.
  • arguments are optional and are enclosed in parentheses. They are used to pass values to the function.
  • The code block contains the instructions or tasks that the function will perform.
  • The return statement is used to indicate the value that the function will return after completing its execution. It is optional and can be omitted if the function does not need to return a value.

Here is an example of a Python function that calculates the square of a number:

def square(number):     
    result = number ** 2     
    return result

## Output

Creating and Calling a Function

To create a function, you simply need to define it using the “def” keyword, followed by the function name and any arguments it accepts. For example:

def greet(name):     
    print(f"Hello, {name}!")  


We have defined a function called “greet” that accepts an argument name. When we call the function using the argument “John”, it will print the message “Hello, John!”.

Types of Functions

Python supports different types of functions, each with its own characteristics and purposes. There are three main types:

Default Arguments

Default arguments are used when you want a function to have a default value for an argument if no value is provided when the function is called.

def multiply(a, b=2):     
    return a * b  

# Output: 
print(multiply(5, 3))  
# Output: 

The multiply function has a default argument “b” with a value of 2. If we don’t provide a value for “b” during the function call, it will use the default value of 2. However, we can also provide a different value for “b” if needed.

Arbitrary Arguments

Arbitrary arguments, also known as variable-length arguments, allow a function to accept any number of arguments. This can be useful when you don’t know how many arguments will be passed to the function:

def average(*numbers):     
    total = sum(numbers)     
    return total / len(numbers)  
print(average(2, 4, 6))  
# Output: 4.0 
print(average(1, 3, 5, 7, 9))  
# Output: 

The average function accepts any number of arguments using the “*numbers” syntax. We can pass multiple numbers to the function, and it will calculate the average by summing them all and dividing by the total count.

Keyword Arguments

Keyword arguments allow you to pass arguments to a function in a non-positional manner, using the argument name instead of the position. This can make the function call more readable and less error-prone:

def greet(name, age):     
    print(f"Hello, {name}! You are {age} years old.")  

greet(name="John", age=25)

Above, we use keyword arguments name=”John” and age=25 to pass values to the “greet” function. We then input which argument corresponds to which value, making the code more readable and self-explanatory.

The Return Statement

The “return” statement is used in Python functions to define the value that the function should return after completing its execution. It is optional and can be omitted if the function doesn’t need to return a value:

def add(a, b):     
   return a + b  
   result = add(3, 5) 

# Output: 

The add function returns the sum of “a” and “b” using the return statement. The returned value is stored in the “result” variable and then printed to the console.

Nested Functions

Nested functions, also known as inner functions, are functions defined inside another function. They have access to the variables and scope of the enclosing function. This allows you to encapsulate functionality and prevent data or functionality from being accessed by other parts of the code.

Recursive Functions

A recursive function is a function that calls itself repeatedly until a specific condition is met. This can be useful when solving problems that can be divided into smaller subproblems. A function to calculate the factorial of a number may be a good example of a recursive function:

def factorial(n):     
    if n == 0:         
        return 1     
        return n * factorial(n - 1)  

result = factorial(5) 
# Output: 120

The factorial function calls itself with a smaller value of “n” until n reaches 0. It then returns 1, which is the base case of the factorial. The function continues to unwind the recursive calls, multiplying the current value of n with the factorial of n – 1 until reaching the original call.


To reinforce your understanding of Python functions, as any other topic, click here for real Python challanges where you will be able to practice functions.

Question 1: Write a program that calculates the squares of numbers ranging from one to eleven using a user-defined function.

def calculate_squares():     
    squares = []     
    for number in range(1, 12):         
        squares.append(number ** 2)     
        return squares  

result = calculate_squares() 
# Output 
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]

Question 2: Write a program that can multiply all the numbers in a list using an inbuilt function.

def multiply_numbers(numbers):     
    result = 1     
    for number in numbers:         
        result *= number     
    return result  
numbers = [2, 4, 6, 8] 
result = multiply_numbers(numbers) 
# Output: 

In the previous exercises, we define two functions to calculate the squares of numbers and multiply all the elements of a list. By calling these functions with appropriate arguments, we can achieve the desired results.




Register New Account
Shopping cart