Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Functions


Functions

The function is a block of code that runs only when it is called.

You can pass data to a function and also return data from a function.

Passing data variables to a function, also known as parameters.

Functions are also called methods.


Create Python Function

In Python, you can create a function using the def keyword.

The sequence of creating function is first def keyword, function_name, parentheses (()) (round brackets), and at the end colon (:).

Example
def python_function():
    print("Hello World!")

In the above example, we created the python_function, and in the function body, we are printing the "Hello world!" text.


Call Python Function

To call the Python function, use the function name with parentheses (()) at the end.

Example
def python_function():
    print("Hello World!")

python_function()
'Hello World!'

After calling the python_function() it executes code written in between them, as you can see in the output "Hello World!" text printed.


Arguments

You can pass information into the function called the arguments.

Arguments should declare inside the function definition parenthesis.

There is no restriction to adding arguments in the function definition you can add as many as you want with comma separation.

Example
def python_function(name):
    print("The company name is", name)

In the above example, we defined the function with a name argument.


Parameters Vs. Arguments.

Parameters and arguments are the same things.

Information passed into a function can be referred to as a parameter or argument.

Function-wise:

Parameters are variables in the function definition enclosed in parentheses.

Arguments are values sent to a function when it is called.


Pass Argument To The Function

Example
def python_function(name):
    print("The company name is", name)

python_function("Google")
python_function("Microsoft")
python_function("Amazon")
'The company name is Google'
'The company name is Microsoft'
'The company name is Amazon'

Here, the python_function() is defined with one argument (name) and passed company names when called.


Pass Multiple Arguments To The Function

Python requires the correct arguments when calling a function, which means a function must be called with two arguments if it has two input parameters, not more or not less.

Example
def python_function(name, country):
    print("The company name is", name)
    print("The company is based in the", country)

python_function("Google", "USA")
'The company name is Google'
'The company is based in the USA'

The python_function() is defined with two arguments (name and country) and passes the company name and country name of a company when called.


Python Function Parameters With Dafault Value

You can set python function parameters with default values.

The default parameter value will use if you do not pass any arguments when calling a Python function.

Example
def python_function(name, country = "USA"):
    print("The company name is", name)
    print("The company is based in the", country)

python_function("Google")
python_function("JIO", "INDIA")
'The company name is Google'
'The company is based in the USA'
'The company name is JIO'
'The company is based in the INDIA'

While calling the python_function() in the first case, we passed only the company name ("Google") and skipped the country name, resulting in the default country name ("USA") being selected.

Similarly, in the second case output, the passed company name and country name arguments are displayed ("JIO", "INDIA").


Pass List As an Argument To The Function

In the Python function, you can pass any data type argument (string, number, list, etc.), and that argument will be treated as the same data type within a function.

Example
def python_function(name_list):
    for name in name_list:
        print("The company name is", name)

company_list = ["Google", "Microsoft", "Amazon"]

python_function(company_list)
'The company name is Google'
'The company name is Microsoft'
'The company name is Amazon'

The above example passes a list data type argument to the python_function().


Python Arbitrary Arguments, *args

If you do not know how many arguments pass the Python function, then put a asterisk (*) before a parameter declaration in parenthesis.

The (*) asterisk-denoted parameters in Python functions are treated as tuple and can be accessed according to your needs.

Example
def python_function(*args):
        for i in range(len(args)):
            print("The company name is", args[i])

python_function("Google", "Microsoft", "Amazon")
'The company name is Google'
'The company name is Microsoft'
'The company name is Amazon'

In the above example, we declare a python_function() with an arbitrary argument (*args) and pass multiple arguments with comma separation while calling the function.


Python Keyword Arguments

It is possible to pass a key-value pair as an argument when calling the function.

Parameter names in function definitions are considered keys.

In this case, the order of the arguments doesn't matter.

Example
def python_function(name, country):
    print("The company name is", name)
    print("The company is based in the", country)

python_function(country = "USA", name = "Google")
'The company name is Google'
'The company is based in the USA'

Here, while calling the python_function() we passed arguments with the key-value pairs, and the order of passed arguments is reverse compared to function-defined parameters.


Python Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments pass the Python function, then put double asterisks (**) before a parameter declaration in parenthesis.

The double (**) asterisk-denoted parameters in Python functions are treated as dictionary and can be accessed according to your needs.

Example
def python_function(**company):
    print("The company name is", company["name"])
    print("The company is based in the", company["country"])

python_function(name = "Google", country = "USA")
'The company name is Google'
'The company is based in the USA'

In the above example, we declare a python_function() with arbitrary keyword arguments (**company) and pass multiple arguments along the key with comma separation while calling the function.


Return Value From The Function

Python functions can return any data type value using the return keyword.

Example
def python_function(name):
    return "The company name is " + name

print(python_function("Google"))
print(python_function("Microsoft"))
print(python_function("Amazon"))
'The company name is Google'
'The company name is Microsoft'
'The company name is Amazon'

Return Multiple Values From The Function

The Python function can also return multiple values separated by commas (,).

Example
def python_function():
    name =  "Google"
    country =  "USA"
    return name, country

company_name, country_origin =  python_function()
print(company_name, country_origin)
'Google' 'USA'

In the above example, we are returning the company name and country name from the python_function().


The pass Statement

The functions in Python should not be empty, if they are empty for any reason, use a pass statement within them to avoid getting an error.

Example
def python_function(name):
    pass

Above example, we used a pass statement to avoid an error.