Contents

Python Functions

A Beginner's Guide to Writing and Using Functions in Python

Website Visitors:

Functions in Python

Python functions are a fundamental concept in the Python programming language. They are a set of instructions that perform a specific task and can be reused throughout the code. Functions are an essential tool for making code more organized, modular, and easy to read.

Defining Python Functions

In Python, you can define a function using the def keyword followed by the function name and a set of parentheses. The function name should be descriptive of what the function does. The parentheses can contain any parameters that the function requires, and are used to pass arguments to the function.

The basic syntax for defining a Python function is as follows:

1
2
3
def function_name(parameters):
    # Function code goes here
    return value
Tip
If you want to print the value returned from a function, you should use print (function_name) command outside the function. In that function should have a return statement. Without this print command, no matter how many times you call the function, it will still result with no output. Because that function is returning something. Outside the function you should capture it with print command and print it on the screen.

The parameters are optional, and if the function doesn’t require any input arguments, you can leave the parentheses empty. The return keyword is used to return a value from the function, which can be assigned to a variable or used in further calculations.

Here is an example of a Python function that adds two numbers together and returns the result:

1
2
3
def add_numbers(x, y):
    result = x + y
    return result

Calling Python Functions

Once a function is defined, you can call it by using its name and passing the required arguments in parentheses. There are different ways to call a Python function, depending on the requirements.

  1. Positional arguments

The most common way to call a Python function is by using positional arguments. In this method, the arguments are passed in the order in which they are defined in the function.

1
add_numbers(2, 3)
  1. Keyword arguments

In Python, you can also use keyword arguments to call a function. This method allows you to pass arguments by specifying their names.

1
add_numbers(x=2, y=3)
  1. Default arguments

Python functions can also have default arguments, which are used when no value is provided for that argument during the function call.

1
2
3
4
5
def add_numbers(x=0, y=0):
    result = x + y
    return result

add_numbers()

Declaring multiple values

Not only specified variables but you can also paas any number of variables as python function arguments. For this you have to specify * and a variable name in the function declaration and pass it as arguments.

In below code, k is the variable and it is used with *. So, we can send multiple values when we call that function.

1
2
3
4
5
6
7
def value (*k):
    result =0
    for x in k:
        result = result + x
    return result
    
print (value (1,3,4))

Different ways in calling functions

1
2
3
4
5
6
7
8
def convertTime(seconds):
    hours = seconds // 3600
    minutes = (seconds - hours * 3600) // 60
    remainingseconds = seconds - hours * 3600 - minutes * 60
    return hours,minutes, remainingseconds

hours, minutes, seconds = convertTime(600)
print (hours,minutes,seconds)

Here, as the function returns 3 values, we can assign them to variables directly as hours,minutes,seconds - convertTime(600). First value from the function will be hours, second value will be minutes and third value will be seconds.

Accept one input while passing multiple values

In cases where you do not know how many values will be passed into the function, you can define a function which accepts one value and call the function with multiple values. Here, you need to pass the values as a list as shown below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

def greeting(friends):
    for friend in friends:
        print("Hi " + friend)
        
greeting(["Raj","Peter"])

# Output:
Hi Raj
Hi Peter

As we have used a list when sending the values to the function, the function accepts it as one value. Inside we have used a for loop to iterate over the values passed into the function.

Function Null value

If you assign a function’s output to a variable and print, when that function is using print inside it, you will get the output as “None” because the function is not returning anything. It is just printing some output. Outside the function you are using print again so it wont work.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def greeting(name):
    print("Hello " + name)

greeting("chris")
# Output: Hello chris

# Assigning function output to variable and printing it
def greeting(name):
    print("Hello " + name)

output = greeting("chris")
print(output)

# Output: 
Hello chris
None

Here it shows none as the print(output) does not have any value as the function is not returning anything. If you change it to return, it will show "Hello chris" in the output instead of none.	

Tips and Tricks

Here are a few tips and tricks to keep in mind when working with Python functions:

  1. Use descriptive function names - Function names should be descriptive and should convey the purpose of the function. This makes the code more readable and easier to understand.

  2. Keep functions simple and focused - Functions should be designed to do one thing well. If a function becomes too complex, it may be a good idea to break it down into smaller functions.

  3. Use default arguments - Default arguments can simplify function calls by providing a default value for arguments that are not always needed.

  4. Document your functions - Documenting your functions with docstrings can help other developers understand how to use the function and what it does.

  5. Test your functions - Always test your functions with a variety of inputs to ensure that they work correctly and handle edge cases appropriately.

Gotchas

Here are a few common gotchas to be aware of when working with Python functions:

  1. Mutable default arguments - Be careful when using mutable objects as default arguments. Since the object is mutable, any changes made to it will persist across function calls.
1
2
3
4
5
6
def append_to_list(item, my_list=[]):
    my_list.append(item)
    return my_list

append_to_list(1)
append_to_list(2)
  1. Variable scope - Variables defined inside a function are not accessible outside the function.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def add_numbers(x, y):
    result = x + y
    return result

add_numbers(2, 3)
print(result) # NameError: name 'result

Here are a few more things to keep in mind when working with Python functions:

1. Functions are first-class objects - In Python, functions are first-class objects, which means they can be passed as arguments to other functions, returned from functions, and stored in variables.

```python
def multiply_numbers(x, y):
    return x * y

def add_numbers(x, y):
    return x + y

def apply_operation(operation, x, y):
    return operation(x, y)

result = apply_operation(multiply_numbers, 2, 3)
print(result) # 6

result = apply_operation(add_numbers, 2, 3)
print(result) # 5
  1. Lambda functions - Lambda functions, also known as anonymous functions, are functions that do not have a name. They are commonly used for small, one-time operations and are defined using the lambda keyword.
1
2
3
multiply_numbers = lambda x, y: x * y
result = multiply_numbers(2, 3)
print(result) # 6
  1. Decorators - Decorators are functions that modify the behavior of other functions. They are defined using the @decorator_name syntax and are commonly used for tasks like logging, timing, and authentication.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper

@log_decorator
def add_numbers(x, y):
    return x + y

result = add_numbers(2, 3)
print(result) # 5
  1. Recursive functions - Recursive functions are functions that call themselves. They are commonly used for tasks that involve repeating patterns, such as traversing a tree or sorting a list.
1
2
3
4
5
6
7
8
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

result = factorial(5)
print(result) # 120

Important points

Here are a few important things to keep in mind when working with Python functions:

  1. Mutable default arguments - In Python, default arguments are evaluated once when the function is defined, not every time the function is called. This can cause unexpected behavior when using mutable objects like lists or dictionaries as default arguments.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def add_item(item, items=[]):
    items.append(item)
    return items

result = add_item('apple')
print(result) # ['apple']

result = add_item('banana')
print(result) # ['apple', 'banana'] - unexpected behavior

# To avoid this, you can use a default value of None and create a new object inside the function
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items
  1. The return statement - The return statement is used to exit a function and return a value. If a function does not have a return statement, it will return None.
1
2
3
4
5
def print_hello():
    print("Hello")

result = print_hello()
print(result) # None
  1. Scope - In Python, variables have different scopes depending on where they are defined. Variables defined inside a function have local scope and are not accessible outside of the function. Variables defined outside of a function have global scope and are accessible throughout the entire program.
1
2
3
4
5
6
def add_numbers(x, y):
    z = x + y
    return z

result = add_numbers(2, 3)
print(z) # NameError: name 'z' is not defined - z is not accessible outside of the function
  1. *args and **kwargs - *args and **kwargs are special syntax in Python that allow a function to accept a variable number of arguments. *args is used to pass a variable number of non-keyword arguments, while **kwargs is used to pass a variable number of keyword arguments.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def add_numbers(*args):
    result = 0
    for num in args:
        result += num
    return result

total = add_numbers(1, 2, 3, 4)
print(total) # 10

def print_values(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_values(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York

Suggested Article

If you’d like to continue reading, checkout our other python commands article here or browse all other topics here.

Conclusion

Understanding these concepts will help you write more effective and efficient Python functions. Overall, Python functions are a powerful tool that can make code more modular, reusable, and easy to read. Understanding how to define and call functions, as well as the tips, tricks, and gotchas, will help you write better Python code.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.