You are on page 1of 10

10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

FUNCTIONS
A function is a block of code that performs a specific task which runs when it is called.Several
types of Functions can be used in Python, each with its capabilities. The first function type is
the built-in function. For example, the ‘print’ function displays text on the screen, or the ‘input’
function allows the user to enter data into the program.

Functions can also be defined to reuse code, known as user-defined functions. User-defined
functions can take arguments, which are values passed into the function to change its
behavior.

1) Every function should start with "def" keyword


2) Every function should have name (not equal to any keyword)
3) parameter / Arguments included in between paranthesis ()
4) Every function named with or without arguments should end with (:)
5) return - empty/value 6) Multi value can be return using tuples

Formally, a function is a useful device that groups together a set of statements so they can be
run more than once. They can also let us specify parameters that can serve as inputs to the
functions.

On a more fundamental level, functions allow us to not have to repeatedly write the same code
again and again. If you remember back to the lessons on strings and lists, remember that we
used a function len() to get the length of a string. Since checking the length of a sequence is a
common task you would want to write a function that can do this repeatedly at command.

Why even use functions?

Put simply, you should use functions when you plan on using a block of code multiple times.
The function will allow you to call the same block of code without having to write it multiple
times. This in turn will allow you to create more complex Python scripts. To really understand
this though, we should actually write our own functions!

We begin with def then a space followed by the name of the function. Try to keep
names relevant, for example len() is a good name for a length() function. Also be careful
with names, you wouldn't want to call a function the same name (such as len).

Next come a pair of parentheses with a number of arguments separated by a comma. These
arguments are the inputs for your function. You'll be able to use these inputs in your function
and reference them. After this you put a colon.

Now here is the important step, you must indent to begin the code inside your function
correctly. Python makes use of whitespace to organize code. Lots of other programing
languages do not do this, so keep that in mind.

Next you'll see the docstring, this is where you write a basic description of the function. Using
Jupyter and Jupyter Notebooks, you'll be able to read these docstrings by pressing Shift+Tab
after a function name. Docstrings are not necessary for simple functions, but it's good practice
to put them in so you or other people can easily understand the code you write.

After all this you begin writing the code you wish to execute.
localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 1/27
10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

The best way to learn functions is by going through examples.

Let's create a function(with docstring)

In [62]: 1 def is_even(i):


2 '''Optional docstring which tells us about the functions,
3 things like what inputs are required, what will the Function return
4 '''
5 x = i%2==0
6 return x
7 print(is_even.__doc__)
8 is_even(8)
9

Optional docstring which tells us about the functions,


things like what inputs are required, what will the Function return

Out[62]: True

In [63]: 1 def is_even():


2 '''Optional docstring which tells us about the functions,
3 things like what inputs are required, what will the Function return
4 '''
5 print(is_even.__doc__)

Optional docstring which tells us about the functions,


things like what inputs are required, what will the Function return

Program: WAP that subtract two numbers using a function

In [64]: 1 def sub(a,b): #function to subtract two numbers


2 return a-b
3 x=8
4 y=6
5 diff = sub #function name assigned to a variable
6 print(diff(x,y)) #function called using variable name

NOTE: You can check your codes on PYTHON TUTOR

Program: Write a function that displays a string repeatedly

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 2/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [65]: 1 def fun():


2 for i in range(5):
3 print("Hello")
4 fun()

Hello
Hello
Hello
Hello
Hello

In [66]: 1 def is_even(num): #Function header


2 #documentation string
3 """
4 This function returns if a given number is odd or even
5 input - any valid integer
6 output - odd/even
7 created on - 16th Nov 2022
8 """
9 if type(num) == int: #Function Body
10 if num % 2 == 0:
11 return 'even'
12 else:
13 return 'odd'
14 else:
15 return 'Incorrect'
16 ​
17 print(is_even.__doc__)
18 print(is_even(7))
19 print(is_even(8))
20 ​

This function returns if a given number is odd or even


input - any valid integer
output - odd/even
created on - 16th Nov 2022

odd
even

Print just shows the human user a string representing what is going on inside the computer.
The computer cannot make use of that printing. return is how a function gives back a value.
This value is often unseen by the human user, but it can be used by the computer in further
functions.

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 3/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [67]: 1 def is_even(num):


2 """
3 This function returns if a given number is odd or even
4 input - any valid integer
5 output - odd/even
6 created on - 16th Nov 2022
7 """
8 if type(num) == int:
9 if num % 2 == 0:
10 print('even')
11 else:
12 print('odd')
13 else:
14 return 'Incorrect'
15 ​
16 print(is_even.__doc__)
17 (is_even('hello'))
18 ​

This function returns if a given number is odd or even


input - any valid integer
output - odd/even
created on - 16th Nov 2022

Out[67]: 'Incorrect'

Using return

So far we've only seen print() used, but if we actually want to save the resulting variable we
need to use the return keyword.

Let's see some example that use a return statement. return allows a function to return a
result that can then be stored as a variable, or used in whatever manner a user wants.

Very Common Question: "What is the difference


between return and print?"
The return keyword allows you to actually save the result of the output of a function as a
variable. The print() function simply displays the output to you, but doesn't save it for
future use. Let's explore this in more detail

Example: Addition function

In [68]: 1 def add_num(num1,num2):


2 return num1+num2

In [69]: 1 add_num(5,8)

Out[69]: 13

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 4/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [70]: 1 # Can also save as variable due to return


2 result = add_num(4,5)
3 print(result)

In [71]: 1 # function
2 # function_name(input)
3 for i in range(1,11):
4 x = is_even(i)
5 print(x)

odd
None
even
None
odd
None
even
None
odd
None
even
None
odd
None
even
None
odd
None
even
None

In [72]: 1 print(type.__doc__)

type(object) -> the object's type


type(name, bases, dict, **kwds) -> a new type

In [73]: 1 print(print.__doc__)

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

2 Point of views

One, who creates the function

Second, who uses the function

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 5/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [74]: 1 def is_even(num):


2 """
3 This function returns if a given number is odd or even
4 input - any valid integer
5 output - odd/even
6 created on - 16th Nov 2022
7 """
8 ​
9 if num % 2 == 0:
10 return 'even'
11 else:
12 return 'odd'
13
14 print(is_even('Hello'))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19256\2960002946.py in <module>
12 return 'odd'
13
---> 14 print(is_even('Hello'))

~\AppData\Local\Temp\ipykernel_19256\2960002946.py in is_even(num)
7 """
8
----> 9 if num % 2 == 0:
10 return 'even'
11 else:

TypeError: not all arguments converted during string formatting

In [95]: 1 def is_even(num):


2 """
3 This function returns if a given number is odd or even
4 input - any valid integer
5 output - odd/even
6 created on - 16th Nov 2022
7 """
8 if type(num)== int:
9 if num % 2 == 0:
10 return 'even'
11 else:
12 return 'odd'
13 else:
14 return 'write integer only'
15 print(is_even('Hello'))

write integer only

Parameters Vs Arguments

Types of Arguments
Default Argument : It assumes a default value if a value is not provided in the function call
for that argument.The default value to an argument is provided by using the assignment

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 6/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

operator (=). User can specify a default value for one or more arguments.

Positional Argument : A positional argument is assigned based on its position in the


argument list.

Keyword Argument : It is assigned based on parameter name.

In [75]: 1 #Giving value to the parameter is known as argument, that's why we are ca
2 #Default Argument
3 def power(a,b):
4 return a**b

In [76]: 1 power(2,3)

Out[76]: 8

In [77]: 1 power(2)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19256\2828352081.py in <module>
----> 1 power(2)

TypeError: power() missing 1 required positional argument: 'b'

In [78]: 1 power()

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19256\964676364.py in <module>
----> 1 power()

TypeError: power() missing 2 required positional arguments: 'a' and 'b'

In [79]: 1 def power(a=1,b=1):


2 return a**b

In [80]: 1 power(2)

Out[80]: 2

In [81]: 1 power()

Out[81]: 1

In [82]: 1 # positional argument or default behaviour of python


2 #Python follows sequence of orders
3 power(2,3)

Out[82]: 8

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 7/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [83]: 1 # keyword argument, pass argument with name


2 power(b=3,a=2)

Out[83]: 8

*args and **kwargs


*args and **kwargs are special Python keywords that are used to pass the variable length
of arguments to a function

In [84]: 1 def multiply(a,b):


2 return a*b

In [85]: 1 multiply(2,3)

Out[85]: 6

In [86]: 1 def multiply(a,b,c):


2 return a*b*c

In [87]: 1 multiply(3,2,4)

Out[87]: 24

In [88]: 1 # *args
2 # allows us to pass a variable number of non-keyword arguments to a functi
3 #create tuple internally or store in it and use loop
4 ​
5 def multiply(*args):
6 product = 1
7 ​
8 for i in args:
9 product = product * i
10 ​
11 print(args)
12 return product

In [89]: 1 multiply(1,2,3,4,5,6,7,8,9,10,12)

(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12)

Out[89]: 43545600

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 8/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [90]: 1 # **kwargs
2 # **kwargs allows us to pass any number of keyword arguments.
3 # Keyword arguments mean that they contain a key-value pair, like a Python
4 # there is an items function in dictionary which separate the key value pa
5 ​
6 def display(**salman):
7 ​
8 for (key,value) in salman.items():
9 print(key,'->',value)
10 ​

In [93]: 1 display(india='delhi',srilanka='colombo',nepal='kathmandu',
2 pakistan='islamabad',bihar ='patna')

india -> delhi


srilanka -> colombo
nepal -> kathmandu
pakistan -> islamabad
bihar -> patna

Points to remember while using *args and **kwargs

order of the arguments matter(normal -> *args -> **kwargs )


The words “args” and “kwargs” are only a convention, you can use any name of your
choice

Program: Using *args to pass the variable length arguments to the function.

In [57]: 1 def add(*nums):


2 sums = 0
3
4 for i in nums:
5 sums = sums + i
6 ​
7 print("Sums:",sums)
8 ​
9 add(3,5)
10 add(4,5,6,7)
11 add(1,2,3,5,6)

Sums: 8
Sums: 22
Sums: 17

Program: Using **kwargs to pass the variable keyword arguments to the function

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 9/27


10/9/23, 10:35 AM FUNCTIONS IN PYTHON - Jupyter Notebook

In [92]: 1 def intro(**data):


2 print("\n Data type of argument:",type(data))
3 ​
4 for key, value in data.items():
5 print("{} is {}".format(key,value))
6 ​
7 intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)
8 intro(Firstname="John", Lastname="Wood",
9 Email="johnwood@nomail.com",
10 Country="Wakanda", Age=25, Phone=9876543210)

Data type of argument: <class 'dict'>


Firstname is Sita
Lastname is Sharma
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>


Firstname is John
Lastname is Wood
Email is johnwood@nomail.com
Country is Wakanda
Age is 25
Phone is 9876543210

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

In [ ]: 1 ​

localhost:8888/notebooks/Downloads/FUNCTIONS IN PYTHON.ipynb 10/27

You might also like