Professional Documents
Culture Documents
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.
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.
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
Out[62]: True
Hello
Hello
Hello
Hello
Hello
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.
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.
In [69]: 1 add_num(5,8)
Out[69]: 13
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__)
In [73]: 1 print(print.__doc__)
2 Point of views
---------------------------------------------------------------------------
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:
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
operator (=). User can specify a default value for one or more arguments.
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)
In [78]: 1 power()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19256\964676364.py in <module>
----> 1 power()
In [80]: 1 power(2)
Out[80]: 2
In [81]: 1 power()
Out[81]: 1
Out[82]: 8
Out[83]: 8
In [85]: 1 multiply(2,3)
Out[85]: 6
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)
Out[89]: 43545600
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')
Program: Using *args to pass the variable length arguments to the function.
Sums: 8
Sums: 22
Sums: 17
Program: Using **kwargs to pass the variable keyword arguments to the function
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1
In [ ]: 1