What is a Python Function?

Functions are a reusable useful block of code that is used to perform a particular action. A Python function essentially helps the coders develop code that is readable, simple, and can be reused to save both time and effort.

What is a function in Python?

A function is a group of related statements that work towards a common goal of performing a task. Functions are important to break the code in smaller chunks of code without which the program becomes huge and unmanageable. Functions also help in reusing the code by simply calling it.

Key takeaways of functions in Python

  • Functions run only when they are called.
  • One can pass data into the functions. They are called parameters or arguments.
  • All Python functions return data.

How to write a function in Python?

  • The functions in Python begin with a keyword ‘def’.
  • Next to def is the unique function name.
  • Then, optional parameters or arguments can be passed into the functions
  • In Python, function header statement ends with a colon ( : ).
  • The set of statements can be written for performing some action.
  • Documentation string called the docstring can be included in the function for the benefit of the user.
  • All the statements within the body of the function should be of same indentation level.
  • A return statement in a function is optional.

An example of a function in Python

def greeting(name):
    """This function greets the user with their name"""
    print("Greetings from Prad Tutorials, " +  name + "!")
greeting("Mr.Lamar")   

Output:

Greetings from Prad Tutorials, Mr.Lamar!

How to call a function in Python?

All the functions have to be called by using the function name by passing the appropriate parameters.

Refer the above example for calling the function.

What is a docstring in Python?

Docstring gives the user the information about the function and is usually the first string in the function.

Including a docstring is a good practice. It is especially true in large projects as it helps the user to stay informed regarding the function.

We use triple quotation marks in the beginning and the end of the sentence to write the docstring. The docstring may extend from a single line to multiple lines.

The function name followed by .__doc__ gives us the docstring.

print(greeting.__doc__)

output:

This function greets the user with their name

Return statement in Python functions

The return statement in functions in Python are optional. The return statement returns a value intended to be returned back from where it was called. In case of no return statement, the function returns a none object.

Example without return statement:

print(greeting("Mr.Simmons"))

output:

Greetings from Prad Tutorials, Mr.Simmons!
None

Example with return statement:

def greeting(name):
    """This function greets the user with their name"""
    print("Greetings from Prad Tutorials, " +  name + "!")
    if(name[0]=='M' and name[1]=='r' and name[2]=='.'):
       return "A male visitor"
    elif((name[0]=='M' and name[1]=='r' and name[2]=='s'and name[3]=='.') or (name[0]=='M' and name[1]=='s')):
       return "A female visitor"
    else:
       return "unknown"

print(greeting("Mrs.Peterson"))

Output:

Greetings from Prad Tutorials, Mrs.Peterson!
A female visitor

Types of functions in Python

There are two types of functions in Python,

  • Built-in functions – These are built into Python and we have to import the packages to call these functions
  • User-defined functions – we define these functions by using the keyword ‘def’.

Scope of variables in Python functions

The scope of a variable is defined as the extent to which the variables are recognized. For example, when a variable is defined within a function, these variables are not recognized outside the functions. These are local to the function.

The lifetime of the variable is defined as the period for which the variable exists in the memory. The lifetime of a variable in a Python function is as long as it executes. The variable ceases to exist once the function returns a value.

def my_function():
 x = 10
 print("This is a value of x inside this function:",x)
x = 20

my_function()

print("This is the value of x outside the function:",x)

output:

Value inside function: 10
Value outside function: 20

What is a parameter?

The parameter meaning is not a lot different from argument. It refers to the variable mentioned in the parentheses while defining the function.

Example:

def greeting(name):
Here ‘name’ is the parameter.

What is an argument?

An argument is the values passed to the function when it is called.

Example:

greeting(“Mrs.Peterson”)

Here Mrs.Peterson is the argument.

The number of arguments passed to the function should be the same as the number of parameters defined. Meaning, if the function has two parameters, the user should send back two arguments while calling the function; not one more or not one less.

Note: People use the word ‘parameter’ and ’arguments’ sometimes interchangeably.

Arbitrary Arguments – *args

If you are unsure of how many arguments a function requires, you can add * before the parameter while defining the function.

Example:

def customers(*names):
  print("The names of the customers from yesterday is/are: ")
  for i in range(len(names)):
      print(names[i])
customers("john Lamar", "amy Tobias", "emily Peterson", "joseph Henderson")

Output:

The names of the customers from yesterday is/are: 
john Lamar
amy Tobias
emily Peterson
joseph Henderson

Arbitrary Arguments – **kwargs

If you are unsure of how many key value pair arguments a function requires, you can add ** before the parameter while defining the function.

Example:

def customers(**names):
  print("The last names of the customers from yesterday is/are: ")
  print(names["lname"])
customers(fname= ["john","amy","emily","joseph"], lname = ["Lamar", "Tobias", "Peterson", "Henderson"])

output:

The last names of the customers from yesterday is/are: 
['Lamar', 'Tobias', 'Peterson', 'Henderson']

Passing a list as arguments

An argument passed in a Python function can be string, list, dictionary, or a number.

Example:

def my_func(fruits):
  for i in fruits:
    print(i)
fruits = ["apple", "banana", "cherry"]
my_func(fruits)

output:

apple
banana
cherry

What is a pass statement in Python?

The body of a function cannot be empty. If the function you define for some reason need not perform any task, a pass statement can be used to avoid errors.

Example:

def my_func():
    pass
my_func()
print("The above function did nothing.")

output:

The above function did nothing.

[wpseo_breadcrumb]

Leave a Comment

Pin It on Pinterest