functions in Python

Python function

Function is a group of statements that performs a specific task, which gets executed only when it is called.


In a program, functions are like subroutines.


You can imagine it like. consider your whole one day as a program and in your whole day you bath, you eat breakfast, lunch , dinner, etc... which can be considered as the subroutine. Which is executed when it is needed.


There are 2 types of functions.

  1. User defined function:- function created by an user.
  2. Built-in function:- function which comes with an application. For example print() function in Python.


Creating a function in Python

To create or to define a function in Python, we make use of the def keyword.


Followed by the function name with parenthesis(which is very important to indicate that it's a function), and a colon at the end.


And after the colon, all the statements related to the function are written, with indentation.


Syntax:-

def function_name():
    statements...


Here is how you can create a function.


Example:- This function will only have a print statement.

Program

def prn():
    print("Hello world")


Calling a function

To execute or call a function, just specify the function name with parenthesis.


Example:- This is how you call the user defined function.

Program

Input


def prn():
    print("Hello world")

prn()

Output

Hello world



Arguments and Parameters

Two terminologies (arguments and parameters) points to the same thing.


Parameters are the variables listed while defining a function.


Arguments are the values passed to the function, when it is called.


Example:- Here, we will create a function which will print the value passed to it, and add '...' at the end.

Program

Input


def prn(val):
    print(val, '...')

prn("Good day")

Output

Good day ...



Position of the arguments with that of parameters should be in sync, if you mess up with that things may go wrong.

Number of arguments

Number of arguments = Number of parameters.


Return values

Use the return keyword, to return value from a function.


Example:- Here we have defined a function that will add two number passed to it and return's the result.

Program

Input


def add(a, b):
    return a + b

result = add(5, 3)
print(result)

 Output

8



When, number of arguments != number of parameters.

Program

Input


 def add(a, b):
    return a + b

result = add(5, 3, 1)
print(result)

Output

Traceback (most recent call last):
  File "C:\Users\user\Desktop\testtttttttttttttt.py", line 4, in <module>
    result = add(5, 3, 1)
TypeError: add() takes 2 positional arguments but 3 were given



It's possible to return more than one value.


Example:- In this we will add and multiply the same numbers passed to the function.

Program

Input


def combo(a, b):
    return (a + b, a * b)

result = combo(5, 3)
print(result)

Output

(8, 15)



Passing List as an argument

It's possible to send any data type as an argument, you can send list, tuple, dictionary, etc... 


Example:- In this example we will pass a list of number to a function, which will add all the numbers in that list.

Program

Input


def add(num):
    c = 0
    for x in num:
        c += x
    return c

result = add([1, 2, 3])
print(result)

Output

6


Recursion in Python

A function calling itself is known as recursion.


It can be considered as a loop, and if terminating point is not defined then it will be an infinite loop.


Example:- Print 'Hello world!' 5 times with recursion.

Program

Input


def helloworld(x):
    if x > 0:
        print("Hello world!")
        # Decrementing the 'x' value
        x -= 1
        # Recursion
        helloworld(x)

helloworld(5)

Output

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!


The pass statement in Python

When defined a function it should have some statements in it, if there are no statements then you will get an error. For some reason you want to keep a function empty you can use the pass keyword.


The pass keyword avoids the error caused by the empty function.


Here is how you can do this stuff.

Program


def func():
    pass


Parameters with default values

If we don't provide the argument then it will take the default value.


Example:- add the numbers send to the function, and if no argument is passed takes the default value '0'.

Program

Input


def add(a=0, b=0):
    return a + b

result = add()
print("Result: ", result)
result2 = add(5)
print('Result2: ', result2)

Output

Result:  0
Result2:  5


Arbitrary arguments

When you don't know the number of arguments to be passed in a function, we can use the concept of arbitrary arguments.


A '*' is placed at the starting of the parameter name, which tells that the function is taking an arbitrary arguments.


Syntax:

def func_name(*parameter_name):
    statements...

Note:- The arguments are converted as tuples to the function. 


If we see the type of 'parameter_name' then we will get it as tuple.

Program

Input


def num(*numbers):
  print(type(numbers))

num(1, 2, 3)

Output

<class 'tuple'>



Example:- In this we will first pass 'fist name'. Then 'first name' and 'last name'. And then 'first name', 'middle name' and 'last name'. And print it out using a function.

Program

Input


def person(*name):
    if len(name) == 1:
        print(name[0])
    elif len(name) == 2:
        print(name[0], name[1])
    else:
        print(name[0], name[1], name[2])

person('John')
person('John', 'Panday')
person('John', 'Michael', 'Panday')

Output

John
John Panday
John Michael Panday



Keyword arguments

In keyword arguments, the arguments are passed as 'key = value' pairs. And the key is parameter name, specified while defining a function. Consider the following example for more clarification.


With this we don't have to worry about the order.


Example:- Printing 'first name', 'middle name' and 'last name' using the keyword arguments concept.

Program

Input


def person(first, middle, last):
    print(first, middle, last)

person(last='Panday', first='John', middle='Michael')

Output

John Michael Panday



Arbitrary keyword arguments

Arbitrary keyword argument is the combination of arbitrary arguments and keyword arguments. 


In arbitrary arguments we use '*' but here we use '**'.


Arguments are passed in the same manner as we pass in keyword arguments. By specifying key=value.


Note:- The arguments are converted in the form of python dictionary. 


If we see the type of 'parameter_name' then we will get it as dict.

Program

Input


def person(**name):
    print(type(name))

person(last='Panday', first='John', middle='Michael')

Output

<class 'dict'>



In dictionary to access value we specify the key.


Example:- Printing 'first name', 'middle name' and 'last name' using the concept of arbitrary keyword arguments.

Program

Input


def person(**name):
    print(name['first'], name['middle'], name['last'])

person(last='Panday', first='John', middle='Michael')

Output

John Michael Panday




Conclusion

Function is collection of ordered statements, which gets executed only when it is called.
Here we have learned how to create a function in Python, how to call a function.

Parameters are the variables listed while defining a function.

Arguments are the values passed to the function, when it is called.

Number of arguments = Number of parameters.

A function calling itself is known as recursion.

Use of the pass statement.

Putting a default value to parameters.

And also learned about arbitrary arguments, keyword arguments and arbitrary keyword argument.






If you have any query, feel free to ask.

إرسال تعليق

If you have any query, feel free to ask.

Post a Comment (0)