Ch no 4 Python Functions,Modules & packages.pptx

gboy4529248 23 views 213 slides Mar 09, 2025
Slide 1
Slide 1 of 213
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213

About This Presentation

Explanation with examples of python functions,modules and packages


Slide Content

Chapter no 4 python functions,modules and packages marks 14

Course outcome Develop Functions for given problems

Type conversion The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. Implicit Type Conversion Explicit Type Conversion

Implicit Type Conversion: In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement. Implicit conversion is when data type conversion take place either during compilation or during run time and is handled by python. Implicit Type Conversion is automatically performed by the Python interpreter. Python avoids the loss of data in Implicit Type Conversion. It is also known as Type coercion.

Ex a = 5 # Integer b = 2.5 # Float result = a + b # Python converts `a` to float automatically print(result) # Output: 7.5 print(type(result)) # Output: <class 'float'>

Example a=12 b=12.34 c=a+b print(c) #Output: 24.34 In above Ex, an int value ‘a’ is added to float value ‘b’, and result is automatically converted to a float value ‘c’ without having to tell the compiler. In this lowest priority data type always get converted to highest priority data type.

Explicit Type Conversion: In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion. This type conversion is also called typecasting because the user casts (change) the data type of the objects. Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function by user. In Type Casting loss of data may occur as we enforce the object to specific data type. Syntax : (required_datatype)(expression)

Converting String to Integer num_str = "100" num_int = int(num_str) # Convert string to int print(num_int, type(num_int)) # Output: 100 <class 'int'>

Converting Float to Integer num_float = 10.99 num_int = int(num_float) # Truncates decimal part print(num_int) # Output: 10

Converting Integer to String num = 123 num_str = str(num) print(num_str, type(num_str)) # Output: '123' <class 'str'>

Converting List to Tuple my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple, type(my_tuple)) # Output: (1, 2, 3) <class 'tuple'>

Converting Integer to Boolean print(bool(0)) # Output: False print(bool(1)) # Output: True print(bool(-10)) # Output: True

Ex a=12 b="20" print("Data type of b before Type Casting:",type(b)) b=int(b) print("Data type of b after Type Casting:",type(b)) #Output Data type of b before Type Casting: <class 'str'> Data type of b after Type Casting: <class 'int'>

List of data type conversion functions 1.int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base if data type is string. eg. >>> print(int('1100',base=2)) 12 2. float() : This function is used to convert any data type to a floating point number eg. >>> print(float('123.45')) 123.45

3. ord() : This function is used to convert a character to integer. eg. >>> print(ord('A')) 65 4. hex() : This function is convert integer to hexadecimal string. eg. >>> print(hex(12)) 0xc 5. oct() : This function is to convert integer to octal string. eg. >>> print(oct(12)) 0o14

6. tuple() : This function is used to convert to a tuple. eg. >>> print(tuple('123')) ('1', '2', '3') 7. set() : This function returns the type after converting to set. eg. >>> print(set('python')) {'t', 'n', 'o', 'h', 'y', 'p'} 8. list() : This function is used to convert any data type to a list type. eg. >>> print(list('123')) ['1', '2', '3'] >>> print(list((1,2,3))) [1, 2, 3]

9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary. eg. >>> print(dict({id:11,'name':'vijay'})) {<built-in function id>: 11, 'name': 'vijay'} 10. str() : Used to convert integer into a string . eg. >>> print(str(10)) ‘10’ 11. complex(real,imag) : : This function converts real numbers to complex(real,imag) number. eg. >>> print(complex(3,6)) (3+6j)

12.eval(str) -Evaluate an string and return an objects. eg. >>> print(eval('4+8')) 12 13.chr(x) -converts an integer to a character eg. >>> print(chr(65)) A

Example a=24 print("str(a)=",str(a)) #The int() function can convert a string representation #of a number in any base (2 to 36) to an integer. b=int('1100',base=2) print("b=",b) c=float('12.34') print("c=",c) list1=list('12345') print(list1) tuple1=tuple('12345') print(tuple1)

Ex continued…. set1=set('python') print(set1) d=hex(12) print("d=",d) e=oct(8) print("e=",e) f=ord('a') print("F=",f) g=chr(65) print("g=",g)

output str(a)= 24 b= 12 c= 12.34 ['1', '2', '3', '4', '5'] ('1', '2', '3', '4', '5') {'y', 'o', 't', 'p', 'n', 'h'} d= 0xc e= 0o10 F= 97 g= A

1.int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base if data type is string. print(int('1100', 2)) # Binary (base 2) → 12 print(int('17', 8)) # Octal (base 8) → 15 print(int('A', 16)) # Hexadecimal (base 16) → 10 print(int('100', 10)) # Decimal (base 10) → 100

Formatting Number and string format() formats a specified value into a specified format. Syntax format(value,format)

Numbers formatting with format()

Formating Number and string sr no format The format we want to format the value into Example 1 b Binary Format >>> x=10 >>> format(x,"b") '1010' 2 c Converts the value into the corresponding unicode character. >>> x=10 >>> format(x,"c") '\n' 3 d Decimal Format >>> x=10 >>> format(x,"d") '10'

sr no format The format we want to format the value into Example 4 e Scientific format with lower case e >>> x=10 >>> format(x,"e") '1.000000e+01' 5 E Scientific format with upper case E >>> x=10 >>> format(x,"E") '1.000000E+01'

Formating Number and string 6 f fix point number format >>> x=10 >>> format(x,"f") '10.000000' 7 g General format >>> x=10 >>> format(x,"g") '10' 8 o Octal format >>> x=10 >>> format(x,"o") '12'

Formating Number and string 9 x Hex format,lower case >>> x=10 >>> format(x,"x") 'a' 10 X Hex format,Upper case >>> x=10 >>> format(x,"X") 'A' 11 % Percentage Format >>> x=10 >>> format(x,"%") '1000.000000%'

Formating Number and string 12 >10s String with width 10 in left justification >>> x='Hello' >>> format(x,">10s") ' Hello' 13 <10s String with width 10 in right justification >>> x='Hello' >>> format(x,"<10s") 'Hello ' 14 < Left align the result(within the available space) >>> x=14.23456 >>> format(x,"<12.3f") '14.235 '

Formating Number and string 15 > Right aligns the result(within the available space) >>> x=11.23456 >>> format(x,'>10.2f') ' 11.23' 16 ^ Centre aligns the result(within the available space) >>> format(x,'^10.2f') ' 11.23 ' 17 _ Use a underscore as a thousand separator >>> format(x,"_") '10_000_000'

Formating Number and string 18 + Use a sign to indicate if the result is positive or negative. >>> x=123 >>> format(x,"+") '+123 19 - Use a sign for negative values only. >>> x=-123 >>> format(x,"+") '-123' 21 , Use a comma as a thousand separator. >>> x=10000000 >>> format(x,",") '10,000,000'

PROGRAM OUTPUT a=24 x=10.23456 y=-12 z=1000000 str="hello" print("a=",format(a,"d")) print("a=",format(a,"c")) print("a=",format(a,"b")) print("a=",format(a,"e")) print("a=",format(a,"E")) print("a=",format(a,"f")) print("a=",format(a,"g")) print("a=",format(a,"o")) a= 24 a= a= 11000 a= 2.400000e+01 a= 2.400000E+01 a= 24.000000 a= 24 a= 30

PROGRAM OUTPUT print("a=",format(a,"x")) print("a=",format(a,"X")) print("a=",format(a,"%")) print("x=",format(x,"<10.2f")) print("x=",format(x,">10.2f")) print("x=",format(x,"^10.2f")) print("x=",format(x,"+")) print("y=",format(y,"-")) print("z=",format(z,",")) print("z=",format(z,"_")) print("str=",format(str,">10s")) print("str=",format(str,"<10s")) a= 18 a= 18 a= 2400.000000% x= 10.23 x= 10.23 x= 10.23 x= +10.23456 y= -12 z= 1,000,000 z= 1_000_000 str= hello str= hello

Built in MATHEMATICAL FUNCTION The math module is a standard module in Python and is always available. It is module that contains some predefined python codes. To use mathematical functions under this module, you have to import the module using import math.

built in function(mathematical) Function Description Example min() Returns smallest value among supplied arguments. >>> min(20,10,30) 10 max() Returns largest value among supplied arguments. >>> max(20,10,30) 30 pow() The pow() function returns the value of x to the power of y(xy).If a third parameter is present,if returns x to the power of y,modulus z. >>> pow(2,3) 8 >>> pow(2,3,2) round() The round() function returns a floating point number that is a rounded version of the specified number,with the specified number of decimals.The default number of decimals is 0,meaning that the function will return the nearest integer. >>> round(10.2345) 10 >>> round(10.7645) 11 >>> round(10.7675,2) 10.77

built in function(math module) sr no Function Description Example 1 ceil() This function returns the smallest integer value greater than the number.If number is already integer,same number is returned. >>> import math >>> math.ceil(2.3) 3 2 floor() This function returns the greatest integer value smaller than the number.If number is already integer,same number is returned. >>> math.floor(2.3) 2 3 cos() This function returns the cosine of the value passed as argument. The value passed in this function should be in radians. >>> math.cos(3) -0.9899924966004454 >>> math.cos(0) 1.0 4 cosh() Returns the hyperbolic cosine of x. >>> math.cosh(3) 10.067661995777765

5 copysign() Return x with the sign of y. on a platform that supports signed zeros,copysign(1.0,-0.0) returns -1.0. >>> math.copysign(10,-12) -10.0 6 exp() The method exp() returns exponential of x. >>> math.exp(2) 7.38905609893065 7 fabs() This function will return an absolute or positive value. >>> math.fabs(20) 20.0 >>> math.fabs(-20) 20.0 8 factorial Returns the factorial of x. >>> math.factorial(5) 120

9 fmod() This function returns x%y >>> math.fmod(4,3) 1.0 10 log(a,(base)) This function is used to compute the natural logarithm(Base e) of a. >>> math.log(14) 2.6390573296152584 11 log2(a) This function is used to compute the logarithm base 2 of a.Displays more accurate result than log(a,2) >>> math.log2(14) 3.807354922057604

12 log10(a) This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10) >>> math.log10(14) 1.146128035678238 13 sqrt() The method sqrt() returns the square root of x for x>0. >>> math.sqrt(16) 4.0 14 trunc() This function returns the truncated integer of x. >>> math.trunc(3.354) 3

Example Program output #log and Exp function import math print("sqrt=",math.sqrt(4)) print("log (2,3)=",math.log(2,3)) print("exp(4)=",math.exp(4)) print("log2(16)",math.log2(16)) print("log10(10000)",math.log10(10000)) print("power=",math.pow(3,2)) sqrt= 2.0 log (2,3)= 0.6309297535714574 exp(4)= 54.598150033144236 log2(16) 4.0 log10(10000) 4.0 power= 9.0

Program output #numerical Maths function import math a = 2.6 b=5 print ("Ceil=",math.ceil(a)) print ("Floor=",math.floor(a)) print ("abs=",math.fabs(a)) print ("fact=",math.factorial(b)) print ("copysign=",math.copysign(5.5, -10)) print ("gcd=",math.gcd(5,15)) Ceil= 3 Floor= 2 abs= 2.6 fact= 120 copysign= -5.5 gcd= 5

Program output #Trignometric Function import math a = math.pi/6 print ("sin(a)=",math.sin(a)) print ("cos(a)",math.cos(a)) print ("tan(a)=",math.tan(a)) print ("degree=",math.degrees(a)) print ("radians=",math.radians(30)) sin(a)= 0.49999999999999994 cos(a) 0.8660254037844387 tan(a)= 0.5773502691896257 degree= 29.999999999999996 radians= 0.5235987755982988

Write use of lambda function in python[2M] The lambda function, which is also called anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax: lambda arguments : expression Example: x= lambda a,b : a*b Print(x(10,5) Output: 50

String built in function In Python, string is a sequence of Unicode character. Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings. We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator (colon). Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We can simply reassign different strings to the same name. We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del.

Built in string function

txt = "hello, and welcome to my world." x = txt.capitalize() print (x) x = txt.casefold() print(x) txt = "banana" x = txt.center(20) print(x) txt = "I love apples, apple are my favorite fruit" x = txt.count("apple") print(x)

output Hello, and welcome to my world. hello, and welcome to my world. banana 2

txt = "My name is Ståle" x = txt.encode() print(x) txt = "Hello, welcome to my world." x = txt.endswith(".") print(x) txt = "H\te\tl\tl\to" x = txt.expandtabs(2) print(x) txt = "Hello, welcome to my world." x = txt.find("welcome") print(x)

output b'My name is St\xc3\xa5le' True H e l l o 7

txt = "Hello, welcome to my world." x = txt.index("welcome") print(x) txt = "Company12" x = txt.isalnum() print(x) txt = "\u0033" #unicode for 3 x = txt.isdecimal() print(x) txt = "50800" x = txt.isdigit() print(x)

7 True True True

txt = "hello world!" x = txt.islower() print(x) txt = " " x = txt.isspace() print(x) txt = "50" x = txt.zfill(10) print(x) txt = "hello, and welcome to my world." x = txt.title() print (x)

True True 0000000050 Hello, And Welcome To My World.

output Hello, and welcome to my world. hello, and welcome to my world. banana 2 b'My name is St\xc3\xa5le' True H e l l o 7 7 True True True True True 0000000050

USER DEFINED FUNCTION

What is a function in Python? In Python, function is a group of related statements that perform a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable. A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Types of Functions Basically, we can divide functions into the following two types: Built-in functions- Functions that are built into Python. User-defined functions - Functions defined by the users themselves.

Creating a Function In Python a function is defined using the def keyword: Syntax Above shown is a function definition which consists of following components. Keyword def marks the start of function header.

A function name to uniquely identify it. Function naming follows the same Parameters (arguments) through which we pass values to a function. They are optional. A colon (:) to mark the end of function header. Optional documentation string (docstring) to describe what the function does. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). An optional return statement to return a value from the function.

How to call a function in python? Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function, use the function name followed by parenthesis: Example-Function without Parameters

Example - calling function through python prompt

Example without parameter def abc(): #function definition print("Simple Function") abc() #function call #Output: Simple Function

Example-Function with Parameters def abc(name): print("Hello",name) abc("Suwarna") #Output: Hello Suwarna

Example-Function with Parameters def square(num): print("square",num*num) square(4) #Output: square 16

Example-Function with Parameters def add(num1,num2): """Add two numbers""" num3 = num1 + num2 return num3 # Driver code num1, num2 = 5, 15 ans = add(num1, num2) print(ans)

Example # A simple Python function to check # whether x is even or odd def evenOdd(x): if (x % 2 == 0): print("even") else: print("odd") # Driver code to call the function evenOdd(2) evenOdd(3) # Output: even odd

Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. 

Example

There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function. Example

Output

Function Arguments You can call a function by using the following types of formal arguments − Required arguments Keyword arguments Default arguments Variable-length arguments

Required arguments Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. To call the function  printme() , you definitely need to pass one argument, otherwise it gives a syntax error as follows −

Required arguments Example def display(str): print(str) display("Hello") #Output: Hello Note: Traceback (most recent call last): File "C:/Users/cm60/AppData/Local/Programs/Python/Python313/aa.py", line 4, in <module> display() TypeError: display() missing 1 required positional argument: 'str'

Keyword arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. We can also make keyword calls to the  printme()  function in the following ways −

Keyword arguments Example def display(str): print(str) display(str="Hello python") #Output: Hello python

example def display(name,age): print("name:",name) print("Age:",age) display(name="meena",age=20) display(age=25,name="meenakshi") #Output: name: meena Age: 20 name: meenakshi Age: 25

Example shows that order of parameters does not matter.

Default arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.  Example

Output

Example Default arguments def display(name,age=20): print("name:",name) print("Age:",age) display(name="meena") display(name="krishna",age=35) #Output: name: meena Age: 20 name: krishna Age: 35

Variable-length arguments The process of defining a function for more arguments than you specified function. These arguments are called  variable-length  arguments and are not named in the function definition, unlike required and default arguments. Syntax

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. Example

Output

example def display(arg1,*list1): print(arg1) for i in list1: print(i) display(10,20,30) display(11,22,33)

# Output: 10 20 30 11 22 33

The  return  Statement The return statement is used to exit a function and go back to the place from where it was called. Syntax of return return [expression_list] This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.

Example def my_function(x): return x * x print(my_function(3)) #Output: 9

def my_function(x): squ=x*x print("squ:",squ) return squ my_function(3) #output: squ: 9

example

Scope of Variables All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python − Global variables Local variables

Global vs. Local variables Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope

example a=10 #Global Variable def show(): b=20 #Local Variable print("Local variable=",b) print("Global variable=",a) show() Output Local variable= 20 Global variable= 10

EXAMPLE

MODULES

What are modules in Python? Modules refer to a file containing Python statements and definitions. A file containing Python code, for e.g.: example.py, is called a module and its module name would be example. We use modules to break down large programs into small manageable and organized files. Modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

Create or writing a Module To create a module just save the code you want in a file with the file extension .py: Example Save this code in a file named mymodule.py

How to import modules in Python? We can import the definitions inside a module to another module or the interactive interpreter in Python. We use the import keyword to do this. To import our previously defined module mymodule ,we type the following in the Python prompt.

Import the module named mymodule, and call the greeting function: Output

example of module #p1.py def add(a,b): result=a+b return result #p2.py import p1 print("Addition:",p1.add(10,20)) #output: Addition: 30

Variables in Module The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc): Example Save this code in the file mymodule.py

Import the module named mymodule, and access the person1 dictionary:

example #mymodule.py person1 = { "name": "John", "age": 36, "country": "Norway" } #main.py import mymodule a = mymodule.person1["age"] b = mymodule.person1["name"] print(a) print(b) #output: 36 John

Import with renaming/Aliasing module We can import a module by renaming it as follows. syntax import module as another_name Example Output

Aliasing Module #p1.py def add(a,b): result=a+b return result #p2.py import p1 as m print("Addition:",m.add(10,20)) #Output: Addition: 30

Python from...import statement We can import specific names from a module without importing the module as a whole. Here is an example. Output

We imported only the attribute pi from the module. In such case we don't use the dot operator. We could have imported multiple attributes as follows.

example #p1.py def add(a,b): result=a+b return result def sub(a,b): result=a-b return result def mul(a,b): result=a*b return result def div(a,b): result=a/b return result

#p2.py from p1 import add,mul print("Addition:",add(10,20)) print("Multiplication:",mul(10,20)) #Output: Addition: 30 Multiplication: 200

Import all names We can import all names(definitions) from a module using the following construct. Example

example #p1.py def add(a,b): result=a+b return result def sub(a,b): result=a-b return result def mul(a,b): result=a*b return result def div(a,b): result=a/b return result

#p2.py from p1 import * print("Addition:",add(10,20)) print("Subtraction:",sub(10,20)) print("Multiplication:",mul(10,20)) print("Division:",div(10,20)) #output: Addition: 30 Subtraction: -10 Multiplication: 200 Division: 0.5

Python built in module 1]Numeric and Mathematical Module 2]Functional Programming Module

1]Numeric and Mathematical Module To provide numeric and mathematical operations , python provides the following built in modules. 1) fractions Module(Rational Numbers) 2)math and cmath Module(Mathematical functions,Mathematical functions for complex number) 3)random Module(Generate Pseudo-random numbers) 4)statistics Module(Mathematical static function) 5)Decimal Module(Decimal fixed point & floating point arithmetic)

Fractions The Fraction Module is used to return the instance with the value=numerator/Denominator. The fractions module provides support for rational number arithmetic. A Fraction is a number which represent a whole number being divided into multiple parts. Python Fractions module allows us to manage fractions in our python programs. For Example from fractions import Fraction print(Fraction(21,49)) Output 3/7

import fractions for deci in [‘0.6’,’2.5’,’2.3’]: f=fractions.Fraction(deci) print(f) Output: 3/5 5/2 23/10

import fractions for num,decimal in [(3,2),(2,5),(30,4)]: fract=fractions.Fraction(num,decimal) print(fract) #Output: 3/2 2/5 15/2

example #convert decimal into fractional number import fractions for decimal in ['0.6','2.5','2.3','4e-1']: fract=fractions.Fraction(decimal) print(fract) #Output: 3/5 5/2 23/10 2/5

Math & cmath modules Python provides two mathematical modules such as math & cmath math Module The math Module is used for various mathematical operations such as finding log , computing sine , calculate square root etc of real numbers . The math module gives us access to hyperbolic, trignometric,&logarithmic functions for real numbers The math Module provide functions such as sqrt(x) factorial(x) sin(x) cos(x) pow(x,y) exp(x) ceil(x)

Example for math module >>> import math >>> math.ceil (1.001 )#returns the smallest integral value greater than the number. 2 >>>import math >>> math.floor (1.001) )#returns the greatest integral value smaller than the number. 1 >>>form math import * >>> sqrt (144) 12

Cmath module Cmath module allows us to work with mathematical functions for complex numbers

Example for cmath module >>> from cmath import * >>> c=2+2j >>> exp (c ) #return exponential -3.0749323206 >>>log(c,2 )#return natural logarithm 1.500000000000001+1.1330

Random module Sometimes we want the computer to pick a random number in a given range , pick a random number from a list etc. So for this we use random modules. This module implements pseudo-random number generators for various distributions.

Example >>> import random >>> print( random.random ()) 0.2170210376653866 #It generate random number in the range(0.0,1.0) >>> print( random.randint (10,20)) 11 # It generate random integer between x and y inclusive. #Random number from list >>> list=[5,2,15,25,70,30] >>> r2= random.choice (list) >>> print(r2) 25

Statistics module It provides access to different statistics functions. Example includes mean,median,mode,standard deviation.

>>> import statistics >>> statistics.mean ([2,5,6,9 ]) #Average 5.5 >>> statistics.median ([ 2,5,6,9,10]) #central value 6 >>> statistics.median ([2,5,6,9]) 5.5 >>> statistics.mode ([6,2,6,9,10,6,8 ])#Repeated value 6 >>> statistics.stdev ([1,1.5,2,2.5,3,3.5,4,4.5,5 ])#standard deviation(spread of values) 1.3693063937629153

Decimal module Decimal numbers are just the floating-point numbers with fixed decimal points We can create decimals from integers,string,float or tuples.

2]Functional Programming Module This modules provide functions and classes that support a functional programming style and general operations. It inlcudes itertools Module functools Module Operator Module

Itertools module For creating iteration or repetition , itertools are used. It provides us various ways to manipulate the sequence while we are traversing it. It includes chain() and cycle() i tertools chain() functions accepts multiple iterable and return a single sequence as if all items belongs to that sequence.

Example from itertools import * for value in chain([1.3,2.51,3.3],[" c++ "," python","java "]): print(value) #Output 1.3 2.51 3.3 C++ Python java

Python itertools cycle() function iterate through a sequence upto infinite. This works just like a circular Linked List Example from itertools import cycle c=0 for i in cycle(["C++","Java"]): print(i) c+=1 if(c>15): break

#Output: C++ Java C++ Java C++ Java C++ Java C++ Java C++ Java C++ Java C++ Java

Functools Module It provides us various tools which allows and encourage us to write reusable code It includes partial() function which are used to replicate existing function with some arguments already passed in it.

Example from functools import partial def multiplier( x,y ): return x*y double=partial( multiplier,y =2) triple=partial( multiplier,y =3) print(‘Double of 5 is {}’.format(double(5))) print(‘Triple of 5 is {}’. format(triple(5))) #Output Double of 5 is 10 Triple of 5 is 15

ex import functools def power( base,exponent ): return base ** exponent square= functools.partial ( power,exponent =2) cube= functools.partial ( power,exponent =3) print(square(5)) print(cube(3 )) #Output: 25 27

map The map() applies the values to every member of the list and returns the result. Syntax result-=map( function,sequence ) Example name=[' sandip ',' amit '] length=list(map( len,name )) print(length) #Output 6,4

Operator module This module provides functions to replace and shorten built in operations for arithmetic and comparison as well as sequence and dictionary related. The operator module supplies function that are equivalent to python operators The Python operator module is one of the inbuilt modules in Python, and it provides us with a lot of functions such as add(x, y), floordiv(x, y) etc., which we can use to perform various mathematical, relational, logical and bitwise operations on two input numbers

It includes Arithmetic and relational operators The Arithmetic Operator are as

The Relational Operations functions are

Comparison operators import operator x, y = 5, 10 print( operator.eq (x, y)) # False (Equivalent to x == y) print(operator.ne(x, y)) # True (Equivalent to x != y) print( operator.lt (x, y)) # True (Equivalent to x < y) print( operator.le (x, y)) # True (Equivalent to x <= y) print(operator.gt(x, y)) # False (Equivalent to x > y) print(operator.ge(x, y)) # False (Equivalent to x >= y)

#Output: False True True True False False

Logical Operators import operator print( operator.and _(True, False)) # False (Equivalent to True & False) print( operator.or _(True, False)) # True (Equivalent to True | False) print( operator.not _(True)) # False (Equivalent to not True) #Output: False True False

Arithmetic operators import operator a, b = 10, 3 print( operator.add (a, b)) # 13 (Equivalent to a + b) print( operator.sub (a, b)) # 7 (Equivalent to a - b) print( operator.mul (a, b)) # 30 (Equivalent to a * b) print( operator.truediv (a, b)) # 3.33 (Equivalent to a / b) print( operator.floordiv (a, b)) # 3 (Equivalent to a // b) print(operator.mod(a, b)) # 1 (Equivalent to a % b) print( operator.pow (a, b)) # 1000 (Equivalent to a ** b)

#Output: 13 7 30 3.3333333333333335 3 1 1000

Namespaces and Scoping A namespace is a  collection of names . A namespace allows us to have  unique  names for each object.  Variables are names (identifiers) that map to objects. A  namespace  is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a  local namespace  and in the  global namespace . If a local and a global variable have the same name, the local variable shadows the global variable. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local. Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. The statement  global VarName  tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

For example, we define a variable  Money  in the global namespace. Within the function  Money , we assign  Money  a value, therefore Python assumes  Money  as a local variable. However, we accessed the value of the local variable  Money  before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

In above Example Each module has display() and name which provide clashes.So Namespace provide means for resolving such problem In python ,each module has its ownspace.This namespace includes the names of all items(function & variable)defined in the module.Therefore two instance of display(),each defined in their own module, are distinguished by being fully qualified with the name of module i.e module1.display() & module2.display()

There are three namespace Local Namespace:The local names inside the function comes under a local namespace. This namespace is created when the function is  called  and the scope ends when the value is  returned . Global Namespace:This namespace includes  names  from the modules that are  imported  in the project. It is created when we include the  module  and it lasts until the  script ends .

Built-in Namespace:This namespace includes  functions  and  exception names  that are built-in in the Python.

Write a program for importing module for addition and subtraction of two numbers[4M]

calculation.py: def add(x,y): return (x+y) def sub(x,y): return (x-y) operation.py: import calculation print(calculation.add(1,2)) print(calculation.sub(4,2))

Packages

Introduction to packages Packages are namespaces which contain multiple packages and modules themselves. They are simply directories Each package in Python is a directory which  MUST  contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. This makes a project (program) easy to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules. Here is an example. Suppose we are developing a game, one possible organization of packages and modules could be as shown in the figure below.

Importing module from a package We can import modules from packages using the dot (.) operator. For example, if we want to import the start module in the above example, it is done as follows. import Game.Level.start Now if this module contains a function named  select_difficulty (), we must use the full name to reference it. Game.Level.start.select_difficulty (2) If this construct seems lengthy, we can import the module without the package prefix as follows. from Game.Level import start

We can now call the function simply as follows. start.select_difficulty(2) Another way of importing just the required function (or class or variable) form a module within a package would be as follows. from Game.Level.start import select_difficulty Now we can directly call this function. select_difficulty(2)

How to create package # suwarna #pack1.py def m1(): print("first module") # suwarna #pack2.py def m2(): print("second module ")

import suwarna.pack1,suwarna.pack2 suwarna.pack1.m1() suwarna.pack2.m2() #Output: first module second module

#p4.py from suwarna.pack1 import m1 m1() #Output: first module

#p5.py from suwarna.pack1 import m1 as function function() #Output: first module

#p6.py from suwarna import pack1,pack2 pack1.m1() pack2.m2() #Output: first module second module

Creating package ex #p1 #d1.py def m1(): print("first module") # p2 # d2.py def m2(): print("second module")

#d3.py import suwarna.p1.d1,suwarna.p2.d2 suwarna.p1.d1.m1() suwarna.p2.d2.m2() #Output: first module second module

Python Standard Library The Python Standard Library is a collection of exact syntax, token, and semantics of Python. It comes bundled with core Python distribution. It includes :-math numpy scipy pandas matplotlib

1. Math This is the most basic math module that is available in Python. It covers basic mathematical operations like sum, exponential, modulus, etc. This library is not useful when dealing with complex mathematical operations like multiplication of matrices. The calculations performed with the functions of the python math library are also much slower. However, this library is adequate when you have to carry out basic mathematical operations.

Example

2. Numpy NumPy is the fundamental package for scientific computing with Python. NumPy stands for "Numerical Python". It provides a high-performance multidimensional array object, and tools for working with these arrays. An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers and represented by a single variable. NumPy's array class is called ndarray . It is also known by the alias array. In NumPy arrays, the individual data items are called elements. All elements of an array should be of the same type. Arrays can be made up of any number of dimensions.

In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total number of elements in that direction. The size of an array is the total number of elements contained in an array in all the dimension. The size of NumPy arrays are fixed; once created it cannot be changed again. Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are that they are fast, easy to work with, and give users the opportunity to perform calculations across entire arrays.

A one dimensional array has one axis indicated by Axis-0. That axis has five elements in it, so we say it has length of five. A two dimensional array is made up of rows and columns. All rows are indicated by Axis-0 and all columns are indicated by Axis-1. If Axis-0 in two dimensional array has three elements, so its length it three and Axis-1 has six elements, so its length is six Advantage of numpy is Array oriented computing Efficient implemented multi dimensional arrays Designed for scientific computation.

Using NumPy, a developer can perform the following operations: 1. Mathematical and logical operations on arrays. 2. Fourier transforms and routines for shape manipulation. 3. Operations related to linear algebra. 4. NumPy has in-built functions for linear algebra and random number generation

Installation of numpy Step1:open command prompt and type comand C:\>python -m pip install numpy Step2:The Package will be installed on your PC.

Ex #one dimensional array import numpy as np a= np.array ([1,2,3]) print(a) #Output: [1 2 3 ] #Two dimensional array import numpy as np a= np.array ([[1,2,3],[4,5,6]]) print(a) #Output : [[1 2 3] [4 5 6]]

import numpy as np a= np.array ([[1,2,3],[4,5,6]])#two dimensional array print(a ) print("Dimension:", a.ndim )#Determines the dimensions of an array. print(" type:",type (a )) print("shape:", a.shape )#A tuple that specifies the number of elements for each dimension of the array . print("size:", a.size )#The total number of elements in the array . print("Type of elements in array:", a.dtype )#Determines the datatype of elements stored in array . print("No of bytes:", a.nbytes )#Determines the byte of elements stored in array.

#output [[1 2 3] [4 5 6]] Dimension: 2 type: <class ' numpy.ndarray '> shape: (2, 3) size: 6 Type of elements in array: int64 No of bytes: 48

Basic array operations import numpy as np a1= np.array ([1,2,3]) a2= np.array ([4,5,6]) print(a1) print(a2) print("Add 1 in each element:",a1+1) print("sum of all array element:",a1.sum()) print("Array sum:",a1+a2) print("Max:",a1.max())

#Output: [1 2 3] [4 5 6] Add 1 in each element: [2 3 4] sum of all array element: 6 Array sum: [5 7 9] Max: 3

Reshaping of array import numpy as np a1= np.array ([[1,2,3],[4,5,6]]) A=a1.reshape(3,2) print(A ) #Output: [[1 2] [3 4] [5 6]]

Slicing of array import numpy as np a1= np.array ([[1,2,3],[4,5,6]]) print(a1[0,2 ]) #3 print(a1[1,2 ])#6

3. SciPy This python math library provides all the scientific tools for Python. It contains various models for mathematical optimization, linear algebra, Fourier Transforms, etc Scipy is pronounced as “sign pi” It is an open source python based library,which is used in mathematics, scientific computing , engineering and technical computing. Most new Data Science features are available in scipy

Installation of Scipy Step1:open command prompt and type comand C:\>python -m pip install scipy Step2:The Package will be installed on your PC.

example

4.pandas It is a python package providing fast , flexible and expressive data structure designed to make working with data structure (tabular,multidimensional) and time series data both easy and intuitive. Pandas is well suited for many different kinds of data such as Tabular data ,Ordered & Un-Ordered Time series data , Arbitary matrix data Data structure used in pandas are Series:-It is one Dimensional Homogeneous Array.The Size of this array is immutable.

DataFrame:-It is Two Dimensional Array.The Size Mutable. Panel:-It is Three Dimensional labelled Array.The Size is mutable

Installation of pandas Step1:open command prompt and type comand C:\>python -m pip install pandas Step2:The Package will be installed on your PC. import pandas as pd

program import pandas as pd import numpy as np a=[[10,20],[30,40]] d=pd.DataFrame(a) print(d) import pandas as pd import numpy as np a=np.array([1,2,3,4,5]) s=pd.Series(a) print(s)

output

5.matplotlib It is plotting Library for Python Programming language and its numerical mathematics extension numpy. It consists of several plots like line ,bar ,scatter , histogram etc. We have to import pylab module of matplotlib import matplotlib.pylab as plt plot() is used to draw the line with the help of data points provided through array show() is used to display the plotted line on the window

Installation of matplotlib Step1:open command prompt and type comand C:\>python -m pip install matplotlib Step2:The Package will be installed on your PC.

import matplotlib.pylab as plt import numpy as np a=[5,10,15,20,30] b=np.array(a) plt.plot(b) plt.show()

output

import matplotlib.pylab as plt import numpy as np x=[2,4,6] y=[5,10,15] plt.bar(x,y) plt.show()

MSBTE QUESTIONS Write use of lambda function in python(2M)] Example module. How to define module. (4M) Explain how to use user defined function in python with example (4M) Write a program for importing module for addition and subtraction of two numbers (4M) Explain use of format() method with example (4M) Write a program illustrating use of user defined package in python (4M) Explain package Numpy with example (6M)

End
Tags