Python Chapter 3 What are the functions and modules in python

 



href="https://blogger.googleusercontent.com/img/a/AVvXsEhzKs6h4p8X-nU-DBYCE6n9Jamdah5LiWiCoWwPVafHvIvWob117CGdUC0LUeBdvLamnH2Ow5G9KZ8aEDWzS8lmWdN4Ye5Yek_yLKcL7g7DjkMTFGiM-Bt5PeU8Xoc-OvDv9wal49e1UTAfFGEmSYi2YfYbddfEC_r1Bix54ZT1b_MoRKvsoAtihve3=s688"
imageanchor="1"
style="margin-left: 1em; margin-right: 1em;"
> border="0"
data-original-height="386"
data-original-width="688"
height="180"
src="https://blogger.googleusercontent.com/img/a/AVvXsEhzKs6h4p8X-nU-DBYCE6n9Jamdah5LiWiCoWwPVafHvIvWob117CGdUC0LUeBdvLamnH2Ow5G9KZ8aEDWzS8lmWdN4Ye5Yek_yLKcL7g7DjkMTFGiM-Bt5PeU8Xoc-OvDv9wal49e1UTAfFGEmSYi2YfYbddfEC_r1Bix54ZT1b_MoRKvsoAtihve3=s320"
width="320"
/>





>




Hello everyone!!!/>



>I hope you understand our last data types in Python; if you have any
difficulty, comment below. I will try to solve your problem. />








So let's get started




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?





    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >The function concept is probably the most important building block
    of any nontrivial software(in any programing language).
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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




    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >A function can take parameters, which are values you supply to
    function to do something utilizing those values.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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. >



  1. Required arguments.

  2. Default arguments.

  3. Keyword arguments.

  4. Variable-length argument.



Required arguments:



    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >The required arguments values passed from calling function to call
    function.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.

    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >

    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'







style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
>


Here is the example,






> >




Default argument values
>




    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >For some functions, we may want to make parameters optional and use
    default values if the user does not want to provide them.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >This is done with the help of default arguments.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >You can specify default argument values for parameters by appending
    to the function definition of the assignment operator (=) followed by
    the default value.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Note that the default argument value should be a constant.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >This is because the values are assigned to the parameters by
    position.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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





style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; color: #0e101a; margin-bottom: 0pt; margin-top: 0pt;"
>









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


>








> async=""
crossorigin="anonymous"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9869442004118280"
>

class="adsbygoogle"
data-ad-client="ca-pub-9869442004118280"
data-ad-format="auto"
data-ad-slot="3195394695"
data-full-width-responsive="true"
style="display: block;"
>






VarArgs parameters




  • 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




  • 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.



>lambda arguments: expression




    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >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.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Filter function expects two arguments, function_object and an
    iterable.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Function_object returns a boolean value.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Function_object is called for each element of the iterable and filter
    returns only those elements for which the function_object returns
    true.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Like the map function, the filter function also returns a list of an
    element.
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; list-style-type: disc; margin-bottom: 0pt; margin-top: 0pt;"
    >
    > data-preserver-spaces="true"
    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; margin-bottom: 0pt; margin-top: 0pt;"
    >Unlike map function, filter function can only have one iterable as
    input. 
    >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; color: #0e101a; margin-bottom: 0pt; margin-top: 0pt;"
    >



> >filter(function_object, iterable) >


    style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; color: #0e101a; margin-bottom: 0pt; margin-top: 0pt;"
    >





> href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgraifcfQx7oNDxheEZGb2UG8sfBh4MiCp1b_hXXTqP14lIZUe9fbFS-0KCqKJw7wH0pm_3sP5ZKFN4NQGtfawDa_NidDeNfBqvMHOAx_f1EdCIaEMsni9QVIMotvjS6NlTeYuqtuilEcM/s925/Screenshot-_105_.webp"
style="margin-left: 1em; margin-right: 1em;"
> border="0"
data-original-height="369"
data-original-width="925"
height="160"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgraifcfQx7oNDxheEZGb2UG8sfBh4MiCp1b_hXXTqP14lIZUe9fbFS-0KCqKJw7wH0pm_3sP5ZKFN4NQGtfawDa_NidDeNfBqvMHOAx_f1EdCIaEMsni9QVIMotvjS6NlTeYuqtuilEcM/w400-h160/Screenshot-_105_.webp"
width="400"
/>













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


>












DocString




  • 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 >


>Let's do it:



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







> > >Congratulations you have created your first module! > >


> >
>




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. > >



>




>THANK YOU! >


async=""
crossorigin="anonymous"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9869442004118280"
>

class="adsbygoogle"
data-ad-client="ca-pub-9869442004118280"
data-ad-format="auto"
data-ad-slot="3195394695"
data-full-width-responsive="true"
style="display: block;"
>

Comments