in , ,

Python Functions

Python Functions

In this article, you’ll find out about functions, what a function is, the syntax components, types, and sorts of functions. Also, you’ll learn to create a function in Python.

What is a function in Python?

In Python, a function is a group of related statements that performs a particular task.

Capacities help break our program into littler and particular lumps. As our program develops bigger and bigger, capacities make it progressively sorted out and sensible.

Moreover, it stays away from redundancy and makes the code reusable.

Syntax of Function

def function_name(parameters):
	"""docstring"""
	statement(s)

Above indicated is a capacity definition that comprises of the following segments.

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example of a function

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

How to call a function in python?

Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters.

>>> greet('worldofitech')
Hello, worldofitech. Good morning!

Note: Try running the above code in the Python program with the function definition to see the output.

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

greet('worldofitech')

Docstrings

The first string after the function header is known as the docstring and is short for documentation string. It is quickly used to clarify what capacity does.

Although optional, documentation is a good programming practice. unless you can remember what you had for dinner last week, consistently document your code.

In the above model, we have a docstring quickly underneath the capacity header. We by and large utilize triple statements so that docstring can reach out up to different lines. This string is accessible to us as the __doc__ attribute of the function.

For example:

Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)

    This function greets to
    the person passed in as
    a parameter

The return statement

The return the statement is used to exit a function and go back to the place from where it was called.

Syntax of return

return [expression_list]

This statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return the statement itself is not present inside a function, then the function will return the None object.

For example:

>>> print(greet("worldofitech"))
Hello, worldofitech. Good morning!
None

Here, None is the returned value since greet() directly prints the name and no return the statement is used.


Example of return

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num


print(absolute_value(2))

print(absolute_value(-4))

Output

2
4

How does the Function work in Python?

How does the Function work in Python?

Scope and Lifetime of variables

The scope of a variable is the part of a program where the variable is perceived. Parameters and factors characterized inside a capacity are not noticeable from outside the capacity. Henceforth, they have a neighborhood scope.

The lifetime of a variable is the period all through which the variable exits in the memory. The lifetime of factors inside capacity is the length of the capacity executes.

They are annihilated once we come back from capacity. Consequently, capacity doesn’t recollect the estimation of a variable from its previous calls.

Here is an example to illustrate the scope of a variable inside a function.

def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

Output

Value inside function: 10
Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value of x to 10, it did not affect the value outside the function.

This is because the variable x inside the function is different (local to the function) from the one outside. Although they have the same names, they are two different variables with different scopes.

On the other hand. variables outside of the capacity are obvious from inside. They have a global scope.

We can read these values from inside the capacity however can’t change (compose) them. So as to change the estimation of factors outside the function, they must be declared as global variables using the keyword global.


Please feel free to give your comment if you face any difficulty here.

For More Latest Articles Click on Below Link

salman khan

Written by worldofitech

Leave a Reply

Python pass statement

Python pass statement

Python Function Arguments

Python Function Arguments