Python Functions

A function is a block of organized code used to perform a specific function. The reusability in any program is important as it reduces the clutter and makes your application modular. Functions help to break the program into small chunks and as a program grows, it makes easier to manage.

How a function is defined in Python?

To create a function in Python, we use def keyword and the name of the function along with its parameters inside the small bracket. The syntax of the function in Python is as below:-

def function_name(parameters):

“””docstring”””
statement(s)
return [expression]
Let us write a simple function to greet your name and pass the name as an argument to the function.

How to call a function in python?

To execute the function, we need to call the function using function name and small brackets as
function_name(parameters)

This program will print the following output:

Hello, John. Good morning!

What is Docstring in Python function?

A docstring is added in the function in order to let developers know what the function does. It helps to maintain good code readability. This string is available to us as __doc__ attribute of the function.

What is the return statement in Python?

The return statement returns the control back to the calling function. If the return statement is not present in the function, then it returns None object.

return [expression_list]

What are Scope and Lifetime of variables in Python?

The scope of the variable plays an important role in Python programming. As different variables are used in the program to store the data, we need to have a clear understanding of what are scopes and its lifetime in the code. The scope of variable means, the portion of the program where the variable is recognized. Parameters and variables insides a function is not visible from outside. Hence, they have a local scope.

A lifetime of a variable is the period in which the variable exists in the memory within program execution. The lifetime of the variable inside a function ends as it gets outs of the function.

What are the different types of functions in Python?

Python provides two kinds of function

  1. Built-in functions
    These are the functions that are defined in the Python library like print(), input(), list() etc.
  2. User-defined functions
    These are the functions that are defined by the user for accomplishing some task. The example can be seen as greet() function that we defined above.
SHARE Python Functions

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share