Stay in touch!

Never miss out on the latest articles and get sneak peeks of our favorite classes.

Python Functions With Examples

ProgrammingPythonSkillsTop List

As an object-oriented programming language, Python relies on building blocks that you can call and reuse. One of these building blocks of Python is functions.

 

Python functions are blocks of codes that perform a specific task. You’ll find helpful built-in functions in Python data libraries, but you can also create your own to manipulate Python strings.

 

Learning to create and call Python functions will help you save time when coding. Functions also allow you to isolate actions to make troubleshooting easier.

 

Read on to learn more about Python functions and get started with some examples.

How Can You Create a Function in Python?

If you need a new function, you can create one by using the def keyword. Next, you’ll have to name your function in parentheses and add a colon. After adding four spaces, you can write the code the function will execute.

 

Here’s what the syntax looks like:

 

def(function_name):   

 

code

quotation marks

You can call a function anywhere in your code to execute a specific action. All you have to do is write the function’s name followed by a colon.

How Do You Call a Python Function?

You can call a function anywhere in your code to execute a specific action. All you have to do is write the function’s name followed by a colon.

 

For instance:

 

print():

What Are Three Types of Python Functions?

Built-in, recursion, and lambda functions are among the most common types of function you’ll encounter when working with Python.

 

Python libraries include a wide selection of pre-built functions you can call in your code. Recursion functions are a type of function that can call themselves when a scenario meets specific requirements. Lambda functions are anonymous functions that can take arguments and modify them.

python functions

Python Functions With Examples

These Python functions are a great place to start if you’re new to programming with this language.

Print()

The print() function is a crucial element of Python. It turns data into text you can display on a webpage or application.

 

You’ll often combine the print() function with other functions to create a block of code that can execute an action and display the output.

 

In this example, we’re creating a function called ‘hello’ that displays a simple text:

 

def hello():

 

print (‘Hello!’)

Sum()

Sum() is a built-in function that allows you to perform basic calculations by adding numbers. You can use sum() to build an online calculator, but it’s also a go-to function for displaying an order summary or a shopping cart in the context of an eCommerce platform.

 

In the following examples, we’re creating a category of numbers before executing the sum() function to add them.

 

numbers = [1, 2, 3, 4, -2]

 

numbers_sum = sum(numbers)

 

print(numbers_sum)

Dict()

Dict() is a function that creates a Python dictionary. A Python dictionary is a collection of items with associated keys and values. It’s a helpful building block you can use to create ordered collections.

 

This example will walk you through creating a dictionary that stores states along with their capitals.

 

dict(state_capitals)

 

state_capitals = {“California”: “Sacramento”, “Texas”: “Austin”, “Florida”: “Tallahassee”}

 

You May Also Like: Introduction to Python with real-life examples

Eval()

The eval() function is another helpful built-in Python function you should use. This function takes a string or code-based input and either evaluates it or executes it as an argument.

 

Here is the syntax to use.

 

eval(string or code-based input)

 

You May Also Like: How long does it take to learn Python?

python functions

Enumerate()

When working with iterable elements, the enumerate() function can give you an associate count and value in the form of a tuple.

 

In the following example, we’re creating a collection of items and using the enumerate() function to turn it into a numbered list.

 

animals = [‘dog’, ‘cat’, ‘rabbit’]

 

enumerate_prime = enumerate(animals)

 

print(list(enumerate_prime))

Help()

This simple function will give you access to built-in documentation and resources from the Python library you’re using.

 

You can also create documentation when working on Python projects and allow other users to access this information with the help() function.

 

Here is an example of how to use this function.

 

help(‘integers’)

 

This function would give you access to documentation about integers, but you can enter any object, class, or function in parentheses.

Input()

When working on projects with interactive elements that allow users to enter text or data, the input() function will come in handy.

 

This Python function can turn anything a user types into a string or tensor. It allows you to place raw data in a container to store it and call it back later.

 

Here is an example where the input() function allows users to type a message.

 

message = input(“Type your message: “)

Type()

The type() function returns the object type. It’s an excellent tool for debugging your code. However, you can use a variation of this function to associate a new type to a given object.

 

If you want to find the type of an object, you should use the syntax type(object).

 

If you want to create a new type for the object, you’ll need to use type(name, bases, dict).

Setattr()

The setattr() function associates an attribute with an object. It can associate a new attribute to the object or change an existing one. The syntax is seattr(object, name, value).

 

In this example, we’re using setattr() to update the status of a client.

 

class Details:

 

name = ‘John’

 

status = ‘standard’

 

setattr(Details, ‘status’, VIP)

Final Thoughts

These Python functions are only a small portion of the 68 built-in functions programmers use. Plus, you can create your own functions to add new capabilities to a Python project.

 

Getting started with some simple functions is a great way to familiarize yourself with object-oriented programming. As you progress, you’ll discover new ways to use these functions and unlock new possibilities by combining them.

 

Related content:

Share this article
Back to top