Python Functions (With Examples) (2024)

A function is a block of code that performs a specific task.

Suppose we need to create a program to make a circle and color it. We can create two functions to solve this problem:

  1. function to create a circle
  2. function to color the shape

Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.

Create a Function

Let's create our first function.

def greet(): print('Hello World!')

Here are the different parts of the program:

Python Functions (With Examples) (1)

Here, we have created a simple function named greet() that prints Hello World!

Note: When writing a function, pay attention to indentation, which are the spaces at the start of a code line.

In the above code, the print() statement is indented to show it's part of the function body, distinguishing the function's definition from its body.

Calling a Function

In the above example, we have declared a function named greet().

def greet(): print('Hello World!')

If we run the above code, we won't get an output.

It's because creating a function doesn't mean we are executing the code inside it. It means the code is there for us to use if we want to.

To use this function, we need to call the function.

Function Call

greet()

Example: Python Function Call

def greet(): print('Hello World!')# call the functiongreet()print('Outside function')

Output

Hello World!Outside function

In the above example, we have created a function named greet(). Here's how the control of the program flows:

Python Functions (With Examples) (2)

Here,

  1. When the function greet() is called, the program's control transfers to the function definition.
  2. All the code inside the function is executed.
  3. The control of the program jumps to the next statement after the function call.

Python Function Arguments

Arguments are inputs given to the function.

def greet(name): print("Hello", name)# pass argumentgreet("John")

Sample Output 1

Hello John

Here, we passed 'John' as an argument to the greet() function.

We can pass different arguments in each call, making the function re-usable and dynamic.

Let's call the function with a different argument.

greet("David")

Sample Output 2

Hello David

Example: Function to Add Two Numbers

# function with two argumentsdef add_numbers(num1, num2): sum = num1 + num2 print("Sum: ", sum)# function call with two valuesadd_numbers(5, 4)

Output

Sum: 9

In the above example, we have created a function named add_numbers() with arguments: num1 and num2.

Python Functions (With Examples) (3)

Parameters and Arguments

Parameters

Parameters are the variables listed inside the parentheses in the function definition. They act like placeholders for the data the function can accept when we call them.

Think of parameters as the blueprint that outlines what kind of information the function expects to receive.

def print_age(age): # age is a parameter print(age)

In this example, the print_age() function takes age as its input. However, at this stage, the actual value is not specified.

The age parameter is just a placeholder waiting for a specific value to be provided when the function is called.

Arguments

Arguments are the actual values that we pass to the function when we call it.

Arguments replace the parameters when the function executes.

print_age(25) # 25 is an argument

Here, during the function call, the argument 25 is passed to the function.

The return Statement

We return a value from the function using the return statement.

# function definitiondef find_square(num): result = num * num

return result

# function callsquare = find_square(3)print('Square:', square)

Output

Square: 9

In the above example, we have created a function named find_square(). The function accepts a number and returns the square of the number.

Python Functions (With Examples) (4)

Note: The return statement also denotes that the function has ended. Any code after return is not executed.

The pass Statement

The pass statement serves as a placeholder for future code, preventing errors from empty code blocks.

It's typically used where code is planned but has yet to be written.

def future_function(): pass# this will execute without any action or errorfuture_function() 

Note: To learn more, visit Python Pass Statement.

Python Library Functions

Python provides some built-in functions that can be directly used in our program.

We don't need to create the function, we just need to call them.

Some Python library functions are:

  1. print() - prints the string inside the quotation marks
  2. sqrt() - returns the square root of a number
  3. pow() - returns the power of a number

These library functions are defined inside the module. And to use them, we must include the module inside our program.

For example, sqrt() is defined inside the math module.

Note: To learn more about library functions, please visit Python Library Functions.

Example: Python Library Function

import math# sqrt computes the square rootsquare_root = math.sqrt(4)print("Square Root of 4 is",square_root)# pow() comptes the powerpower = pow(2, 3)print("2 to the power 3 is",power)

Output

Square Root of 4 is 2.02 to the power 3 is 8

Here, we imported a math module to use the library functions sqrt() and pow().

More on Python Functions

User Defined Function Vs Standard Library Functions

In Python, functions are divided into two categories: user-defined functions and standard library functions. These two differ in several ways:

User-Defined Functions

These are the functions we create ourselves. They're like our custom tools, designed for specific tasks we have in mind.

They're not part of Python's standard toolbox, which means we have the freedom to tailor them exactly to our needs, adding a personal touch to our code.

Standard Library Functions

Think of these as Python's pre-packaged gifts. They come built-in with Python, ready to use.

These functions cover a wide range of common tasks such as mathematics, file operations, working with strings, etc.

They've been tried and tested by the Python community, ensuring efficiency and reliability.

Default Arguments in Functions

Python allows functions to have default argument values. Default arguments are used when no explicit values are passed to these parameters during a function call.

Let's look at an example.

def greet(name, message="Hello"): print(message, name)# calling function with both argumentsgreet("Alice", "Good Morning")# calling function with only one argumentgreet("Bob")

Output

Good Morning AliceHello Bob

Here, message has the default value of Hello. When greet() is called with only one argument, message uses its default value.

Note: To learn more about default arguments in a function, please visit Python Function Arguments.

Using *args and **kwargs in Functions

We can handle an arbitrary number of arguments using special symbols *args and **kwargs.

*args in Functions

Using *args allows a function to take any number of positional arguments.

# function to sum any number of argumentsdef add_all(*numbers): return sum(numbers)# pass any number of argumentsprint(add_all(1, 2, 3, 4)) 

Output

10

*kwargs in Functions

Using **kwargs allows the function to accept any number of keyword arguments.

# function to print keyword argumentsdef greet(**words): for key, value in words.items(): print(f"{key}: {value}")# pass any number of keyword argumentsgreet(name="John", greeting="Hello")

Output

name: Johngreeting: Hello

To learn more, visit Python *args and **kwargs.

Also Read:

  • Python Recursive Function
  • Python Modules
  • Python Generators
Python Functions (With Examples) (2024)

FAQs

What are the 4 types of functions in Python? ›

This article explains different types of Functions in Python. The functions explained are Built-in Functions, User-defined Functions, Recursive Functions, Lambda Function. A function is a block of code in Python that performs a particular task.

What is a Python function example? ›

Some Python library functions are: print() - prints the string inside the quotation marks. sqrt() - returns the square root of a number. pow() - returns the power of a number.

What are the 3 different function in Python? ›

These three functions, which provide a functional programming style within the object-oriented python language, are the map(), filter(), and reduce() functions.

What are common functions in Python? ›

The 10 common Python functions we discussed, including `print()`, `len()`, `type()`, `str()`, `int()`, `float()`, `input()`, `range()`, `append()`, `split()`, and `join()`, form the bedrock of many basic and advanced Python operations.

What are the five functions in Python? ›

Python Built in Functions
FunctionDescription
eval()Evaluates and executes an expression
exec()Executes the specified code (or object)
filter()Use a filter function to exclude items in an iterable object
float()Returns a floating point number
63 more rows

What are the 4 main data types in Python? ›

The data types in Python that we will look at in this tutorial are integers, floats, Boolean, and strings. If you are not comfortable with using variables in Python, our article on how to declare python variables can change that.

How can I write a function in Python? ›

Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. Add statements that the functions should execute.

What is the main function in Python? ›

In Python, the role of the main function is to act as the starting point of execution for any software program. The execution of the program starts only when the main function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.

What is init in Python? ›

The __init__ method is crucial in object-oriented programming in Python. It is a special method automatically called when an object is created from a class. This method allows us to initialize an object's attributes and perform any necessary setup or initialization tasks.

How to call a function in Python? ›

To call a function in Python, you simply type the name of the function followed by parentheses (). If the function takes any arguments, they are included within the parentheses.

What are the two main types in Python? ›

Different Kinds of Python Data Types

Some built-in Python data types are: Numeric data types: int, float, complex. String data types: str. Sequence types: list, tuple, range.

What is Python used for? ›

Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as accountants and scientists, for a variety of everyday tasks, like organizing finances.

What are good functions in Python? ›

  • 21 Most Frequently Used Built-in Functions In Python — A Beginners Guide. RS Punia 💠 ...
  • print() The print() function is used to output text or variables to the console. ...
  • type() In Python, everything is an object. ...
  • len() The len() function is used to get the length of an object. ...
  • id() ...
  • range() ...
  • str() ...
  • list()
Mar 28, 2023

What are regular functions in Python? ›

Python has two primary regular expression functions: match and search. The match function looks for a match only where the string starts, whereas the search function looks for a match everywhere in the string.

What is an example of a function Python? ›

print() Parameter Example

There is a function in Python called print() . It does many things, but one simple thing it does is take in a parameter value and print it out to the screen. Though unglamorous, this is a way to see function call and parameters in action.

How many functions are in Python? ›

The built-in Python functions are pre-defined by the python interpreter. There are 68 built-in python functions.

What is the type function in Python? ›

Python type() is a built-in function that is used to return the type of data stored in the objects or variables in the program. For example, if a variable contains a value of 45.5 then the type of that variable is float.

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 6654

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.