Python Functions: Everything You Need to Know

Introduction

Up until now, you have used a lot of functions in Python, most prominently the print function. Now, it is time to write your own Python functions. Welcome! I'm Abdullah from PythonSage!, and let's quickly talk about what a function is in programming.

Python Functions: Everything You Need to Know


A function is a piece of code responsible for carrying out a specific task. It encapsulates several lines of code into one line (the line when you call the function) and makes it accessible throughout the whole program. This improves your program's readability because you don't have to repeat yourself if you want to do several tasks at different positions. It also helps you fix bugs in your code; if a function is specific to one task and that task is carried out throughout the program, you only have to fix it in one place.

Let's dive in and declare our first function in Python. In this example, we will declare a function that adds two variables together.

Declaring a Function in Python

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

Here’s how it works:

Keyword def: This tells Python that we are declaring a new function.

Function Name add: Function names follow the same rules as variable names (e.g., they can not start with a number and can not include spaces).

Parentheses (x, y): These are the function parameters and values that are passed to the function and can be used inside it.

Colon: This indicates the start of the function body.

Indented Code: The indented lines under the function signature are the code that is always executed when we call that function.

In this function, we add x and y together and return the result using the return statement.

Calling a Function

To use the add function, you call it in your main program and store the result:

result = add(42, 23)

print(result)

#This will output 65 since 42 + 23 equals 65.

Multiple Return Statements

Functions can have multiple return statements. Let’s create a function that returns the maximum of two variables:

def maximum(x, y):

    if x > y:

        return x

    else:

        return y

Here’s how to use this function:

result = maximum(42, 23)

print(result)

#This will output 42 because 42 is greater than 23.

No Return Value

Functions can also modify passed arguments without returning a value. Let’s double the elements of a list:

def double(l):

    l.extend(l)

 

numbers = [1, 2, 3]

double(numbers)

print(numbers)

#This will output [1, 2, 3, 1, 2, 3]. The list numbers is modified inside the function.

Placeholder Functions

When planning your functions but not ready to implement them yet, use pass or ... (ellipsis) as placeholders:

def not_implemented_yet(x):
    pass

def another_placeholder(x):
    ...

These functions do nothing when called but let your code run without errors.

Returning Multiple Values

Python allows returning multiple values from a function using tuples:

def quadratic_formula(a, b, c):

    discriminant = b**2 - 4*a*c

    if discriminant less than "Use-less-than-operator"  0:

        return None, None

    x1 = (-b + discriminant**0.5) / (2*a)

    x2 = (-b - discriminant**0.5) / (2*a)

    return x1, x2

 x1, x2 = quadratic_formula(1, -7, 12)

print(x1, x2)

#This will output 4.0 3.0, the roots of the equation x^2 - 7x + 12 = 0.

Default Parameter Values

Functions can have default parameter values:

def greet(name, msg="Hello"):

    print(f"{msg}, {name}!")

 greet("Abdullah")

greet("Python Sage Family", "Enjoy Python Functions")

#This will output: Hello, Abdullah! Enjoy Python Functions, Python Sage Family!

Arbitrary Number of Arguments

Use *args to pass an arbitrary number of arguments:


def sum_all(*args):

    total = 0

    for num in args:

        total += num

    return total

 print(sum_all(1, 2, 3, 4, 5))

#This will output 15.

Arbitrary Keyword Arguments

Use **kwargs to pass an arbitrary number of keyword arguments:

def print_info(**kwargs):

    for key, value in kwargs.items():

        print(f"{key}: {value}")

 
print_info(name="Abdullah", age=24, city="Saudi Arabia")

#output:

#name: Abdullah

#age: 24

#city: Saudi Arabia

Watch this Video to Learn More:


Conclusion

Functions are essential in Python for organizing and simplifying your code. By understanding how to declare, call, and use various types of functions, you can write more efficient and readable programs.

I hope this blog post helps you get started with Python functions! Feel free to ask any questions or leave feedback in the comments section below.

This post is brought to you by PythonSage, your go-to resource for learning and mastering Python. Whether you're a beginner or an experienced coder, Python Sage provides tutorials, examples, and exercises to help you excel. Visit our website for more great content and join our community of Python enthusiasts.

Happy coding!

Post a Comment

Previous Post Next Post