Python Chapter 3 What are the functions and modules in python
Python Chapter 3 What are the functions and modules in python
So let's get started
Default argument values
VarArgs parameters
The return statement
Global Variable
DocString
Making your own Modules
Congratulations you have created your first module!
In this chapter, we are going to learn functions and modules in Python.
Course content:
Functions:
- Function parameters.
- Default argument values.
- Keyword argument.
- varargs parameter.
- The return statement.
- Local variable.
- The global statement.
- Lamda, map, and filter function.
- DocString
Modules:
- Introduction.
- The import module.
- Making your own module.
- The dir function.
So let's see........
What is the function?
- Functions are reusable pieces of programs. They allow you to give the name to a block of statements, allowing you to run that block using a specified name anywhere in your program and any number of times. This is known as calling the function.
- The function concept is probably the most important building block of any nontrivial software(in any programing language).
- Functions are defined using the "def" keyword. After this keyword comes an identifier name for the function, followed by the pair of parentheses that may enclose some variables' names and the final colon that ends the line. Next follows the block of statements that are part of this function.
1. How to call a function?
def say_hello(Name, Sname):
print("Hello",Name,Sname)
say_hello("Himanshu","Jungare")
Output=Hello Himanshu Jungare
def f1():
print("Hello")
print("This is a first pgm")
f1()
f1()
f1()
Output=Hello
This is a first pgm
Hello
This is a first pgm
Hello
This is a first pgm
Function parameters
- A function can take parameters, which are values you supply to function to do something utilizing those values.
- These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs.
- Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way.
- The names given in the function definition are called parameters whereas the values you supply in the function are called arguments.
def print_max(a,b):
if a>b:
print(a ,"is maximum ")
elif a==b:
print(a,"is equal to",b)
else:
print(b,"is maximum")
print_max(2,4)
Output=4 is maximum
x=9
y=10
print_max(x,y)
Output=10 is maximum
Passing arguments to the function
- In Python, there are 4 types of argument.
- Required arguments.
- Default arguments.
- Keyword arguments.
- Variable-length argument.
Required arguments:
- The required arguments values passed from calling function to call function.
- The user-defined function can also not argue. The number of arguments should be matched in the function call and function definition in the required arguments. Otherwise, it yields an error.
-
def f1(x):
print("The value of x is: ",x)
n=input("Enter the number: ")
f1(n)
Output=Enter the number: 4
The value of x is: 4
def f1(x,y):
print("The value of x is: ",x)
n=input("Enter the number: ")
f1(n)
Output=TypeError: f1() missing 1 required positional argument: 'y'
Here is the example,
- For some functions, we may want to make parameters optional and use default values if the user does not want to provide them.
- This is done with the help of default arguments.
- You can specify default argument values for parameters by appending to the function definition of the assignment operator (=) followed by the default value.
- Note that the default argument value should be a constant.
- Only those parameters which are at the end of the parameter list can be given default argument values i.e. you cannot have a parameter with a default argument value preceding a parameter without a default argument value in the function's parameter list
- This is because the values are assigned to the parameters by position.
- For example, def func(a,b=5) is valid , but def func(a=5,b) is not valid
def say(message,times=3):
print(message * times)
say("Hello ")
Output=Hello Hello Hello
say("World ",5)
Output=World World World World World
def say1(message='hi',times=3):
print(message*times)
say1('Hello ')
Output=Hello Hello Hello
say1()
Output=hihihi
def say2(message='hi',times):
print(message*times)
Output=SyntaxError: non-default argument follows default argument
Keyword Argument:
- If we have some functions with many parameters and we want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments -
- We use the name (keyword) instead of the position (which we have been using all
- along) to specify the arguments to the function.
- There are two advantages-
- One, using the function is easier since we do not need to worry about the order of
- the arguments.
- Two, we can give values to only those parameters to which we want to, provided, that the other parameters have a default argument value
def add(x,y):
c=x+y
print('x value is ',x)
print('y value is ',y)
print("Sum of x and y is ",c)
add(100,200)
Output=x value is 100
y value is 200
Sum of x and y is 300
n1=int(input("Enter the number: "))
n2=int(input("Enter the number: "))
add(n1,n2)
Output=Enter the number: 5
Enter the number: 4
x value is 5
y value is 4
Sum of x and y is 9
add(y=n1,x=n2)
Output=x value is 4
y value is 5
Sum of x and y is 9
def add(x=20,y=30):
c=x+y
print('x value is ',x)
print('y value is ',y)
print("Sum of x and y is ",c)
add()
Output=x value is 20
y value is 30
Sum of x and y is 50
n1=int(input("Enter a first number: "))
n2=int(input("Enter a second number: "))
add(x=n1)
Output=Enter a first number: 5
Enter a second number: 4
x value is 5
y value is 30
Sum of x and y is 35
add(23)
Output=add(23)
add(23)
x value is 23
y value is 30
Sum of x and y is 53
- Sometimes we might want to define a function that can take any number of parameters, i.e. variable number of arguments, this can be achieved by using the stars.
def total(initial=5, *numbers,
**keywords):
- When we declare a starred parameter such as *numbers, then all the positional
- arguments from that point till the end are collected as a tuple called 'numbers'.
- Similarly, when we declare a double-starred parameter such as **keywords, all the keyword arguments from that point until the end are collected as a dictionary called 'keywords'.
def total(initial=5,*numbers,**keywords):
count=initial
print("Initial: ",count)
print("Numbers:",numbers)
for n in numbers:
count=count+n
print("Keywords: ",keywords)
for key in keywords:
count=count+keywords[key]
print("Count: ",count)
total(10,21,3,32,vegetables=100,fruits=50)
Output=Initial: 10
Numbers: (21, 3, 32)
Keywords: {'vegetables': 100, 'fruits': 50}
Count: 216
total(3,2,4,56,54,vegetables=182,fruits=32,bags=2)
Output=Initial: 3
Numbers: (2, 4, 56, 54)
Keywords: {'vegetables': 182, 'fruits': 32, 'bags': 2}
Count: 335
total()
Output=Initial: 5
Numbers: ()
Keywords: {}
Count: 5
- The return statement is used to return from a function i.e. break out of the function.
- We can optionally return a value from the function as well.
- Note that a return statement without a value is equivalent to return None.
- None is a special type in Python that represents nothingness.
- For example, it is used to indicate that a variable has no value if it has a value of none.
- Every function implicitly contains a return None statement at the end unless you have written your own return statement.
- Multiple values also can be returned by using tuple unpacking methodology.
def add(x,y):
s=x+y
x=x+1
y=y+1
return(s,x,y)
add(23,34)
Output=(57, 24, 35) Dont't get confused here read it carefully
n1=int(input("Enter the 1st number: "))
n2=int(input("Enter the 2nd number: "))
add(n1,n2)
Output=Enter the 1st number: 5
Enter the 2nd number: 8
(13, 6, 9) Dont't get confused here read it carefully
s1,y1,x1=add(n1,n2)
print("The sum of numbers is: ",s1)
print("The 1st number is: ",x1)
print("The 2nd number is: ",y1)
Output=
The sum of numbers is: 13
The 1st number is: 9
The 2nd number is: 6
Lambda, map, and filter functions
- The Lambda operator or lambda function is used for creating small, one-time, and anonymous function objects in Python.
- The Lambda operator can have any number of arguments, but it can have only one expression. It cannot contain any statements and it returns a function object which can be assigned to any variable.
- Map functions expect a function object and any number of iterables like a list, dictionary, etc. It executes the function_object for each element in the sequence and returns a list of the elements modified by the function object.
- Filter function expects two arguments, function_object and an iterable.
- Function_object returns a boolean value.
- Function_object is called for each element of the iterable and filter returns only those elements for which the function_object returns true.
- Like the map function, the filter function also returns a list of an element.
- Unlike map function, filter function can only have one iterable as input.
def multiply2(x):
return x*2
res=multiply2(4)
print(res)
Output=8
x=map(multiply2,[1,2,3,4,5])
print(x)
Output=map at 0x1213635ed30>
print(type(x))
Output=class 'map'>
print(list(x))
Output=[2, 4, 6, 8, 10]
x=map(lambda x:x*2,[2,3,4,5])
print(list(x))
Output=[4, 6, 8, 10]
list_a=[{'name':'python','points':10},{'name':'java','points':8}]
print(list_a)
Output=[{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
Recursive function
- Recursion is the process of defining something in terms of itself.
- A function that calls itself is called a recursive function.
- Through Recursion one can easily solve problems while its iterative solution is very big and complex.
def decrement(a):
if (a>0):
print(a)
decrement(a-1)
else:
return()
n=int(input("Enter the number: "))
decrement(n)
Output=Enter the number: 5
5
4
3
2
1
Local Variable
- When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function.
- Variable names are local to the function. This is called the scope of the variable.
- All variables have the scope of the block they are declared in starting from the point of definition of the name.
def func():
x5=2
print("Changed the value of x to ",x5)
func()
print("The value of x5 ",x5)
Output=Changed the value of x to 2
NameError: name 'x5' is not defined
x=50
def func():
print("x is ",x)
func()
print('x is still ',x)
Output=x is 50
x is still 50
Global Variable
- If we want to assign a value to a name defined at the program's top-level (i.e., not inside any kind of scopes such as functions or classes), then we have to tell Python that the name is not local, but it is global.
- We do this using the global statement.
- It is impossible to assign a value to a variable defined outside a function without the global statement.
- We can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function).
- However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is.
- Using the global statement makes it amply clear that the variable is defined in an outermost block.
x=50
def func():
x=2
print("Changed local x to ",x)
func()
print("x is still ",x)
Output=Changed local x to 2
x is still 50
x=50
def func():
global x
x=2
print("Changed the value of x to ",x)
func()
print("The value of x ",x)
Output=Changed the value of x to 2
The value of x 2
x=3
print("The value of x ", 3)
Output=The value of x 3
- Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings.
- DocStrings are an important tool that you should use since it helps document the program better and makes it easier to understand.
def print_max(x,y):
'''Print the maximum of two numbers.
The two values must be integers.'''
#Convert
x=int(x)
y=int(y)
if x>y:
print(x," is greater/maximum")
else:
print(y," is greater/maximum")
print_max(3,2)
Output=3 is greater/maximum
print(print_max.__doc__)
Output=print(print_max.__doc__)
print(print_max.__doc__)
Print the maximum of two numbers.
The two values must be integers.
Modules
- We have seen how we can reuse code in our program by defining functions once.
- What if we wanted to reuse several functions in other programs that we write?
- The answer is Modules.
- There are various methods of writing modules, but the simplest way is to create a file with a .py extension that contains functions and variables. A module can be imported by another program to make use of its functionality.
- This is how we can use the Python standard library as well.
import math
print("The square root of 16 is ",math.sqrt(16))
Output=The square root of 16 is 4.0
from math import sqrt
print("The square root of 16 is ",sqrt(16))
Output=The square root of 16 is 4.0
from math import (sqrt,gcd)
print("Square root of 16 is ",sqrt(16))
Output=Square root of 16 is 4.0
print("GCD of 16,4 is ",gcd(16,4))
Output=GCD of 16,4 is 4
Making your own Modules
- Creating your own module is easy, we have been doing it all along.
- This is because every python program is also a module.
- One just have to sure it has a .py extension
Filename: sum_module.py
Write this code:
v1=100
def s(x,y):
return (x+y)
import sum_module
print(sum_module.s(100,200))
print(sum_module.v1)
Output=300
100
from sum_module import (s,v1)
print(s(100,200))
print(v1)
Output=300
100
from sum_module import *
print(s(100,200))
print(v1)
Output=300
100
The dir function
- We can use the built-in dir function to list the identifiers that an object defines.
- For a module, the identifiers include the functions, classes and variables defined in that module.
- When we supply a module name to the dir() function, it returns the list of the names defined in that module.
import math
help(math.sqrt)
dir(math)
Output=Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
['__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',etc.............
I hope that you have understood all the topics of this chapter.
Now we will meet in the next chapter.
Join the conversation