python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx

yuvarajkumar334 230 views 178 slides Jun 14, 2024
Slide 1
Slide 1 of 190
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

About This Presentation

PYTHON NOTES


Slide Content

Data Analytics Using Python Python Python is a programming language that combines the features of C and Java. When the programmers want to go for object orientation, python offers class and objects like java. Python was developed by Guido Van Rossum in the year 1991 at the center of Mathematics and computer Science managed by the Dutch Government. Van Rossum picked the name python for the new language from the TV show , “Monty Python’s Flying Circus”. The logo of Python shows two intertwined snakes.

Features of Python Simple : python is a programming language when we read a python program , we feel like reading English sentences. It means more clarity and less stress on understanding the syntax of the language. Easy to Learn : Python uses very few keywords. Its programs use very simple structure so developing programs in python become easy. Open Source : There is no need to pay for python software. Python can be freely downloaded from www.python.org . High Level Language: High Level languages use English words to develop programs. These are easy to lern and use. Platform Independent: When a python program is compiled using a python compiler, it generates byte code. Python’s byte code represents a fixed set of instructions that run on all operating systems and hardware. Using a python virtual machine, anybody can run these byte code instructions on any computer system.

Features of Python Huge Library: Python has a big library which can be used on any operating system. Programmers can develop programs very easily using the modules available in the python library. Scripting Language: A scripting language is a programming language that does not use a compiler for executing source code . Rather, it uses an interpreter to translate the source code into machine code while running. Database Connectivity: Python provides interfaces to connect its programs to all major databases like Oracle, Sybase or MySql. Scalable: Python programs are scalable since they can run on any a platform and use the features of the new platform effectively. Interpreter: A software which converts high-level language instructions line-by-line into machine-level language is called an interpreter.

Parts of Python programming Language Identifiers Keywords Statements and Expressions Variables Operators Precedence and associativity Data types. Indentation Comments

Parts of Python programming Language Identifier: Identifier is a user-defined name given to a variable, function, class, module or object. The identifiers are formed with a combination of alphabets (A-Z or a-z), digits and underscore. All identifiers are case sensitive. Here are naming conventions for python identifiers. Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with a two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscore, the identifier is language defined special name. Example: sum, total, s1, gross_salary

Parts of Python programming Language Variable: A variable is a name used to store a value. The variable may change its value during the execution of a program. In Python, a variable need not be declared with a specific type before its usage. The type of it will be decided by the value assigned to it. Example: a = 10 b = “hello” c = 5.5 Rules to follow when naming variables Variable name can contain letters , numbers and underscore. Variable name cannot contain spaces and other special characters . Variable name should not start with a digit. Variable names are case sensitive i.e. ‘Total’ different from ‘total’. Keywords cannot be used as a variable name. Example: valid variable names : total, a1,net_salary invalid variable names: 1a, total salary

Parts of Python programming Language Keywords : Keyword is a special word which is having a predefined meaning. The meaning of the keyword cannot changed by a user. Keywords are building blocks of the programming language. Example: and, as, assert, break, continue, while and so on Statements and Expressions: A statement is a unit of code the python interpreter can execute . There are mainly four types of statements in python. Assignment statement ii) print statement iii) conditional statement iv) Looping statements Assignment statement: we assign a value to a variable using the assignment statement by using assignment operator(=) Example: a = 10 c = a + b a, b, c = 10, 20, 30

Parts of Python programming Language p rint statement: print is a function which takes string variables as a argument to display it on the screen. Example: a = 10 print(a) Optional arguments with print statement : Sep: Python will insert a space between each of the arguments of the print function. There is an optional argument called sep. For Example sep = “ : ” would separate the argument by a colon and sep = “ ## “ would separate the arguments by two hash symbols. For example: print(“a” , ”b”, “c”, “d”, sep =“ ;”) output: a;b;c;d

Parts of Python programming Language Optional arguments with print statement : e nd: The print function will automatically advance to the next line. For example: print(“a”) print(“b”) print(“c”, end = “ “) print(“d”) output: a b c d

Parts of Python programming Language Expression: An expression is a combination of operands and operators is called an expression. The expression in python produces some result or value after being interpreted by the python interpreter. for example: a = 10 a = a + 10 print(a) output is 20

Operators, precedence and associativity Operator is a symbol that perform either arithmetic or logical operation. Arithmetic operators: Operator meaning example + addition c = a + b - subtraction c = a - b * multiplication c = a * b / division c = 5 / 2 will give 2.5 // floor division c = 5 // 2 will give 2 % modulo division c = 5 % 2 will give 1 ** exponent e = a ** b means a to the power of b

Assignment operator These operators are useful to store the right side value into a left side variable. For Example: a = 10 c = a + b a += b (a = a + b) Unary minus operator : The unary minus operator is denoted by the symbol (-). When this operator is used before a variable, its value is negated. For example: n = 10 print(-n) The output is -10

Relational Operators Relational operators compare two quantities. The following are the relational operators. The following are the relational operators. <, >, == , <= , >= , != The relational expression will return a value True or False depending on the condition. Example: print(5 > 3) returns True print(5 < 3) returns False

Logical operators Logical operators are useful to construct compound condition. A compound is a combination of more than one simple condition. Each of the simple condition is evaluated to true or false and then the decision is taken to know whether the total condition is true or false. Logical operators are ‘and’ , ‘or’ and ‘not’ For Example: print(5 > 2 and 8 > 3) returns True print(5 > 8 or 3 > 9) returns False print( not( 5 > 8)) returns True

Precedence and Associativity (order of operation) When an expression contains more than one operator, the evaluation of operators depends on the precedence of operators. The python operators follow the precedence rule(Which can be remembered as PEMDAS) Parenthesis have the highest precedence in any expression. The operations within parenthesis will be evaluated first. Exponentiation: Has the 2 nd precedence ,but ,it is right associative. if there are two exponentiation operations continuously, it will be evaluated from right to left. For Example : print( 2 ** 3 ** 2) 2^3^2= 2^9 = 512

Precedence and Associativity (order of operation) Multiplication and division are next priority : Out of these operations , whichever comes first in the expression is evaluated. p rint( 5 * 2 / 4) = 5 *2 = 10 10/4 = 2.5 p rint( 8 / 2 * 3) = 8 / 2 = 4 4 * 3 = 12 Additions and subtractions are least priority: Out of these operations , whichever appears first in the expression is evaluated i.e. they are evaluated from left to right. print(5 + 3 – 2) = 5 + 3 = 8 – 2 = 6 print(8 -2 + 3) = 8 – 2 = 6 + 3 = 9

Precedence and Associativity (order of operation) Ex example: x = 1 + 2 ** 3 / 4 * ( 5 – 2) x = 1 + 2 ** 3 / 4 * 3 x = 1 + 8 / 4 * 3 x = 1 + 2 * 3 x = 1 + 6 x = 7

Data types Data types specify the type of data stored in a variable like numbers and characters. Basic data types are . Numbers . Boolean . Strings. List, Tuple, Dictionary, None Numbers: Integers ,floating point numbers and complex numbers fall under python number category. They are defined as int, float and complex class in python. Integers can be of any length. It is only limited by the memory available. A floating number contains a decimal point and have accuracy of 15 decimal places. Complex numbers are written in the form x + y i. Where x is the real part and y is the imaginary part. Boolean: Python Boolean type is one of the built-in datatypes provided by python, Which represents one of the two values i.e. True or False

Data Types Strings A string consists of a sequence of one or more characters, which can include letters ,numbers and other type of characters. A string can also contain spaces. You can use single quotes or double quotes to represent strings and it is also called a string literal. Multline strings can be denoted using triple quotes. For Example: s1 = ‘welcome to python ‘ s2 = “welcome to python” s3 = ‘’’ welcome to python ‘’’

Data Types List: A list is formed by placing all the items inside square brackets[], separated by commas it can have any number of items and they may or may not be different types (integers, float, string,etc) for example lst = [ 1,2,3,4.5,”python”] Tuple : A tuple is defined as ordered collection of python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. We can represent tuples using parenthesis (). for example t = (1,2,3,4.5,”python”) Dictionary: Dictionary is an unordered collection of data values. Dictionary consists of key value pair. In python, a dictionary can be created by placing a sequence of elements within curly braces({ }), separated by comma. Dictionary holds pairs of values, one being its key and other corresponding pair element its key: value. Values in a dictionary can be any data type and can be duplicated, where as keys cannot be repeated and must be immutable. For example = { “usn”: 123, “name”: “xyz”, “marks”: 50}

Data Types None: None is another special datatype in python. None is frequently used to represent the absence of a value. for example: money = none

Indentation Code block1 begins Code block2 begins Code block3 begins Code block2 continues Code block1 continues Usually, we expect indentation from any program code, but in python it is a requirement and not be matter of style. This makes code look clearer and easier to understand and read. Any statements written under another statement with the same indentation is interpreted to belong to the same code block. If there is a next statement with less indentation to the left, then it just means the end of the previous code block. In other words, if a code block has to be deeply nested statements need to be indented further to the right. In the above diagram , code block2 and code block3 are nested under block1. Usually four white spaces or tab space used for indentation. In correct indentation will result in indentation error.

Comments As programs get bigger and more complicated, they get more difficult to read. It is often difficult to look at a piece of code and figure out what it is doing or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and in python they start with the “#” symbol. Comments are non-executable statements. There are two types of comments: 1. Single line comment 2. Multiline comment Single line comment: These comments start with a hash symbol (#) and are useful to maintain that entire line till the end should be treated as comment. for example: # program to add two numbers

Comments 2. Multiline comments: When we want mark several lines as comment, then writing # symbol in the beginning of every line will be tedious job. Instead of starting every line with # symbol, we can write the “ “ “(triple double quotes) or ‘ ‘ ‘(triple single quotes) in the beginning and ending of the block as: “ “ “ welcome to python Hello world data analytics “ “ “ or ‘ ‘ ‘ welcome to python Hello world data analytic ‘ ‘ ‘

Reading input and output To accept an input from keyboard, python provides the input function. This function takes a value from the keyboard and return it as a string. For Example: str = input() # this will wait until we enter a string print(str) It is a better idea to display a message to the user so that the user understands what to enter. This can be done by writing a message inside input() function as For Example: str = input(“enter your name”) print(str)

Reading input and output We can use the int() function before the input()function to accept an integer from the keyboard as For Example: x = int(input(“enter x”)) print(x) Similarly to accept a float value from the keyboard, we can use float() function along with the input() function For Example: x = float ( input(“enter x”)) print(x)

Reading input and output # A Python program to accept 3 integers in the same line separated by # space and display their sum For Example: a, b, c = [ int(x) for x in input(“enter 3 no's”).split()] print(“sum = “ , (a + b + c)) # A Python program to accept 3 integers in the same line separated by # comma and display their sum For Example: a, b, c = [ int(x) for x in input(“enter 3 no's”).split ( “,”)] print(“sum = “ , (a + b + c )) # Evaluating an expression entered from keyboard F or Example: x = eval(input(“enter an expression”)) print(x) input: 10 + 5 – 4 output : 11

Printing Output Format operator: The format operator , % allows us to construct strings, replacing parts of the strings with the data stored in variable. For Example, the format sequence ”%d” means that the operand should be formatted as an integer. a = 10 “%d” %a “ 10” A format sequence can appear anywhere in the string. So you can embed a value in a sentence. For Example: a = 10 “ The value of a is %d” % a output: “the value of a is 10”

Printing Output If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order. The following example uses “%d” to format an integer, %g to format a floating point number, and “%s” to format a string. “in %d years I spotted %g %s” %(3, 0.1 , “camels”) output: “in 3 years I spotted 0.1 camels Format function: is one of the string formatting methods in python3, Which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. Two types of parameters: Positional argument Keyword argument

Printing Output Positional argument : It can be integers, floating point numbers, strings, characters and even variables. Keyword argument : They are essentially variable storing some value, which is passed as parameter. Positional arguments are placed in order. For Example: print(“ {0} college {1} department” . format(“Atria”, mca”)) Output: Atria college mca department Positional arguments are not specified, by default it starts positioning from zero For Example: print(“ {} college {} department” . format (“Atria”, mca”)) Output: Atria college mca department . Printing Output Printing Output

Printing Output Keyword arguments are called by their keyword name. For Example: print(“MCA department has {0} sections in {college}”. f ormat(“2”, college = “Atria”)) Output: MCA department has 2 sections in Atria f- strings : Formatted strings or f-strings were introduced in python 3.6. A f-string is a string literal that is prefixed with ‘f’ . These strings may contain replacement fields, which are expressions enclosed within curly braces { }. For Example: a = 10 print(f “the value of a is { a}) output : the value of a is 10

Type conversion functions Python provides built-in functions that convert values from one type to another. i nt(): ex1: int(“32”) # string to integer 32 ex2: int(“hello”) value error ex3: int(3.56) # float to integer 3 ex4: int(-2.34) # float to integer -2 float() : ex1: float(32) # convert integer to float 32.0 ex2: float(“3.124”) convert string to float 3.124 str() : ex1: str(32) “ 32” ex2: str(3.124) “3.124”

The type() function t ype() function is used to know the datatype of the value. The expression in parenthesis either a value or a variable. Ex1: type(10) output: <class int> Ex2: type(10.5) output: <class float> Ex3: type (“hello”) output: <class str> Ex4: a = 10 type(a) output: <class int>

The is operator The ‘is’ operator is useful to compare whether two objects are same or not. It will internally compare the identity number of the objects. If the identity numbers of the objects are same, it will return True; Otherwise, it returns False. For Example: a = 25 id(a) 1670954952 b = 25 id(b) 1670954952 a is b output: True When two variables are referring to same object, they are called as identical objects. When two variables are referring to different objects, but contain a same, they are known as equivalent objects.

The is operator For Example: s1 = input(“enter s1”) # if input hai s2 = input(“enter s2”) # if input hai s1 is s2 # output false s1 == s2 # output true

Control flow statement i f statement: T his statement is used to execute one or more statement depending one or more statement depending on whether a condition is True or not. The general form is: if condition: statements First, the condition is tested. If the condition is True, then the statements given after colon(:) are executed. If the condition is False, then the statements mentioned after colon are not executed. # program to find the biggest of two numbers a = int(input(“enter a”)) b = int(input(“enter b”)) big = a if b > big: big = b print(big)

The if – else statement The if – else statement executes a group of statements when a condition is true; Otherwise, it will execute another group of statements . The general form of if – else statement is as follows: if condition: statements1 else: statements2 If the condition is True, then it will execute statements1 and if the condition is False, then it will execute statement2.

The if – else statement # To check whether the given number is even or not n = int(input(“enter n”)) if n % 2 == 0: print(“even no”) else: print(“odd no”)

The if – elif – else statement Sometimes, the programmer has to test multiple conditions and execute statements depending on those conditions if – elif – else statement is useful in such situations. The general form of if – elif – else statement is as follows if condition1: statement1 elif condition 2: statement2 elif condition 3: statement3 - - else: statement4

The if – elif – else statement Here, the conditions are tested from top to bottom as soon the true condition is found, then the associated statements are executed. After the execution, the control will be transferred below if—elif –else statement. Example : # to check whether the given number is positive, negative or # equal to zero n = int (input(“enter n “)) if n > 0: print(“positive number”) elif n < 0: print(“negative number”) else: print(“equal to zero”)

Nested if statement In if statement , another if statement exists then it is called nested if statement. # program to check whether the given number is positive and even or # odd n = int(input(“enter n”)) if n > 0: if n % 2 == 0: print(“positive and even number”) else: print(“ number is positive and odd”) else: print(“the number is not positive”)

Looping statements Repeatedly executing a block of statements is called a loop. While loop: The while loop is useful to execute a group of statements several times depending on the condition is true or false. The general form is as follows: while condition: statements Python interpreter first checks the condition. If the condition is true, then it will execute the statements written after colon( :) . After executing the statements, it will go back and check the condition again. If the condition is again found to be true, then it will execute the statements. In this way, as long as condition is true, python interpreter executes statements again and again. Once the condition is found to be false, then it will come out of the loop.

While loop # program to display numbers from 1 to 10 x = 1 while x <= 10: print(x) x = x + 1

The for loop The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the sequence. The for loop work with sequence like string, list and tuple. The syntax of the for loop is given below: For var in sequence: statements The first element of the sequence is assigned to the variable written after for and then statements are executed. Next, the second element of the sequence is assigned to the variable and then the statements are executed second time. In this way, for each element of the sequence , the statements are executed once. So, the for loop is executed as many times as there are number of elements in the sequence.

The for loop # a python program to display the characters of a string using for loop str = “hello” for ch in str: print(ch, end = “ “) Output: h e l l o Syntax of for loop with range() function: for variable in range(start, end, steps): statements to be repeated The start and end indicates starting and ending values in the sequence, where end is excluded in the sequence that is sequence is up to end – 1. The default value of start is 0. The argument steps indicates the increment / decrement in the values of the sequence with the default value as 1. Hence the argument steps is optional.

The for loop # program to print the message multiple times for i in range (3): print(“hello”) Output: hello hello hello # program to print numbers in sequence for i in range(5): print(i, end = “ “) output: 0 1 2 3 4 #program to display numbers from 5 to 1 for i in range(5,0,-1): print(i, end = “ “) Output: 5 4 3 2 1

for loop # program to display odd numbers from 1 to 10 using range function for i in range(1,10,2): print( i , end = “ “) output: 1 3 5 7 9 Nested loops It is possible to write one loop inside another loop is called nested loops. For Example: for i in range(2): for j in range(3): print(“ I =“, I “\t”, “j = “,j) Output: i = 0 j =0 i = 1 j = 0 i = 0 j = 1 i = 1 j = 1 I = 0 j = 2 I = 1 j = 2

The break statement The break statement is used to terminate a loop when an unusual condition occurs in the body of the loop. For Example: for i in range(10): if i == 4: break print( i , end = “ “) output: 0 1 2 3

The continue statement The continue statement is used in a loop to go back to the beginning of the loop. It means, when continue is executed, the next repetition will start when continue is executed, the subsequent statements in the loop are not executed. # program to print odd numbers for i in range(1,10): if i % 2 == 0: continue else: print(I, end = “ “) Output: 1 3 5 7 9

Functions A sequence of instructions intended to perform a specific independent task is known as a function. You can pass data to be processed, as parameters to the function. Some functions can return data as a result. Function types Built-in types User defined functions Built-in Function Python provides a number of built-in functions that we can use without needing to provide the function definition Built-in functions are ready to use functions

Functions Commonly used modules: Math functions: python has a math module that provides most of the frequently used mathematical functions. Before we use the those functions, we need to import the module as below. ex: import math Some of the functions in math module are: Function Description ceil(x) Raises x value to the next higher integer. If x is an integer, then same value is returned. Ex: ceil(4.3) gives 5

Math functions Function Description floor(x) Decreases x value to the previous value. If x is an integer, then the same value is returned. Ex: floor(4.5) gives 4 d egree(x) converts angle value x radians into degree radians(x) converts x value from degrees into radians

Math functions Functions Description sin(x) gives sine value of x. Here x value is given in radians cos(x ) gives cos value of x. Here x value is given in radians fabs(x) gives the absolute value for positive quantity of x Ex: fabs(-4.5) gives 4.5 f atorial(x) Returns factorial of x.

Math functions Functions Descriptions f mod(x, y) Returns remainder of division of x and y. fmod() is used to calculate the modulus of float values ex: fmod(14.5,3) gives 2.5 modf(x) returns float and integral parts of x ex: modf(2.56) (0.56,2.0) sqrt(x) returns positive square root of x sqrt(16) = 4

Math functions Function Description pow(x, y) Raises x value to the power of y ex: pow(2,3) = 8 gcd( x, y) gives the greatest common divisor of x and y. gcd(14,10) = 2 t run(x) The real value of x is truncated to integer value. Trun(12.3) gives 12. Math.pi the mathematical constant

Random numbers Most of the programs that we write take predefined input values and produces expected output values such programs are said to be deterministic. Making a program truly non deterministic turns out to be not so easy, but there ways to make it at least seem non-deterministic. One of them is to use algorithms that generate pseudo-random numbers. The function random returns a random float between 0.0 to 0.1 and for integers( 1 and 100 ) Python has a nodule called random, in which functions related to random numbers are available. To generate random numbers. Consider an example to generate random numbers import random for i in range(5): x = random.random() print(x)

Random numbers The function randint() takes the parameters low and high, and returns an integer between low and high, and returns an integer between low and high (including both) import random random.randint(5,10) The output may be between 5 and 10. for ex: 6, or, 7 or 9 To choose an element from a sequence from a sequence at random you can use choice import random t = [ 1, 2, 3, 4] random.choice(t) Output: it can choose any element from the list

Some of Built-in Functions max() ex: max(“hello world”) output: w display the character having maximum ASCII code m in() ex: min(‘hello world’) output: ‘ ‘ display the character having minimum ASCII code l en() ex: len(“ hello”) output: 5 display the length of the string

User-defined functions The general syntax of a user-defined function: def fname(arg list): statement1 statement2 -------------- --------------- statement n return value def : is a keyword indicating it as a function definition f name : is any valid name given to the function a rg list : is list of arguments taken by a function. These are treated as inputs to the function from the position of function call. They may be zero or more arguments to a function. statements : are the list of instructions to perform required task r eturn: is a keyword used to return the output value. This statement is optional.

User-defined functions The first line in the function def fname(arg list): is known as function header function definition. The remaining lines constitute function body. The function header is terminated by a colon and body must be indented. To come out of the function, indentation must terminated. # program to add two numbers using function def add( a , b): c = a + b return c s = add(10,20) # function call print(s)

V oid Functions A function that performs some task, but do not return any value to the calling function is known as void function. Example: def add(): a = 10 b = 20 c = a + b print(c) add() #function call Fruitful functions: The function which returns some result to the calling function after performing a task is known as fruitful function. All built-in functions are called fruitful function.

Scope and lifetime of variables All variables in 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 variable. There are two basic scope of variables in python: global variables local variables Global versus local variables: Variables that are defined inside a function body have a local scope, and those defined outside have global scope. This means that local variables can be accessed only inside the function in which they are declared. Where as global variables can be accessed throughout the program body by all function.

Scope and lifetime of variables # program to demonstrate global and local variables total = 10 def add(a, b): total = a + b # here total is local variable print(total) add(10,20) print(total) # here total is global variable output: 30 10

Default arguments For some functions, you may want to make some parameters optional and use default values. In case the user does not want provide values for them. This is done with the help of default argument values. Default argument values can be specified for parameters by appending to the parameter name in the function definition. The assignment operator(=) followed by the default value Note that the default argument value should be a constant Only the parameters which are at the end of the parameterlist can be default values. For example: def add(a, b = 5): is valid def add(a = 5,b): is invalid

Default arguments # program to demonstrate default arguments def add(a, b = 5): c = a + b print(c) add(10,20) add(30) If we specify the argument values, then it will not take default value. If do not have a corresponding value for a argument then it will take a default value. Output for first function is 30 Output for first function is 35

Keyword Arguments If you have some functions with many parameters and you want to specify only some of them, then you can give values for each parameters by naming from them, this is called keyword arguments. We use the name instead of the position to specify the arguments to the function. There are two advantages: 1. Using the function is easier since we do not need to worry about the order of the arguments 2. We can give values to only those parameters to which we want to provided that the parameter have default argument values.

Keyword Arguments # program to demonstrate keyword arguments def func(a, b = 5 , c = 10): print(“a is “,a, “and b is”, b, ”and c is”,c ) func(3,7) func(25,c = 24) func(b = 20, a =100) Output: a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 20 and c is 10

*args and ** kwargs Sometimes you 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. *args and ** kwagrs are mostly used as parameters in function definition. *args and ** args allows you to pass a variable number of arguments to the calling function. Here variable number of arguments means that the user does not know in advance about how many arguments will be passed to the called function. *args as parameters in function definition allows you to pass a non- key worded, variable length tuple argument list to the called function. **kwargs as parameter in function definition allows you to pass key worded. Variable length dictionary argument list to the called functions. *args come after all the positional parameters and **kwargs must come right at the end.

*args and ** kwargs # program to demonstrate *args and ** kwargs def func(a = 5, *numbers,**names): print(“a = “, a) for i in numbers: print( i ) for fp,sp in names.items(): print(fp,sp) func(10,20,30,40,xxx = 40, yyy = 50 zzz = 60) output : a = 10 20 30 40 zzz 60 yyy 50 xxx 40

Command line arguments The ‘sys’ module provides a global named ‘argv’ that is list of extra text that the user can supply when launching an application from the command prompt. # Python program to display command line arguments import sys n = len( sys.argv ) print(“no of command line args =‘, n) print(“the arguments are”, args) print(“the args one by one”) for x in args: print(x) To run a program like this C:\> python cmd.py 10,20,hello output : no of command line args = 3 The arguments are [‘10’,’20’,’hello’] The args one by one 10 20 hello

Command line arguments #python program to add numbers using command line arguments import sys args = sys.argv sum = 0 for x in args: sum = sum + int(x) print(sum) To run this program c:\> python sum.py 10 20 30 output 60

Module-2 String: A string is a sequence of characters, Which include letters, numbers, punctuation marks and spaces. Creating and storing strings A string can be created enclosing text in single or double quotes. s = “hello” s1 = ‘python’ To nullify the effect of escape characters, we can create the string as ‘raw’ string by adding ‘r’ before the string as s = r “welcome to \t core python \n learning” print(s) Output: welcome to \t core python \n learning

Strings Length of a string : Length of a string represents the number of characters in a string. To know the length of a string, we can use the len() function. s = “hello” l = len(s) print(l) output: 5 Basic string operations: Repeating the strings : The repetition operator is denoted by * symbol and is useful o repeat the string for several times. For ex: str * n repeats the string for n times. s = “hai” print(s * 3) output: hai hai hai

Strings 2. Concatenation of strings: We can use ‘+’ on strings to attach a string at the end of another string. s1 = “hello” s2 = “world” s3 = s1 + s2 print(s3) Output: Hello world 3. In operator: The in operator returns true if string or character found in the main string. It returns false if the string or character is not found in the main string.

Strings # python program to check whether a substring exists in main string or # not str = input(“enter a main string”) sub = input(“enter a sub string”) if sub in str: print(“sub string present in main string”) e lse: print(“sub string is not present in main string”)

Strings 4. Comparing strings : We can use the relational operators like >, ==, <, == or != operators to compare two strings. They return Boolean value i.e. either True or False depending on the strings being compared. s1 = “box” s2 = “boy” if s1 == s2: print(“same”) else: print(“not same”) This code returns ‘not same’ as the strings are not same. While comparing the strings, python interpreter compares them by taking them in English dictionary order. The string which comes first in the dictionary order will have low value than the string which comes next. It means ‘A’ is less than ‘B’ which is less than ‘C’ and so on.

Strings # python program to compare two strings s1 = input(“enter a string1”) s2 = input(“enter a string 2”) if s1 == s2: print(“strings are equal”) elif s1 < s2: print(“strings are not equal”) else: print(“s1 is greater than s2”)

Strings # Accessing characters in string by index number (Traversing in a st ring”) str = “hello” index = 0 while index < len(str): print(str[index], end = “ “) index = index + 1 # output h e l l o # Another way to traversal a string str = “hello” for ch in str: print(ch, end = “ “) # output h e l l o

Strings Accessing characters in string by index number: We can get at any single character using an index specified in square brackets. The index value can be an integer and starts at zero. For example: str = “python” Character index str = “python” print(str[0]) # output p print(str[3]) #output h P Y T H N 1 2 3 4 5

S trings Python supports negative indexing starting from the end of the string as shown below. Character index str = “python” print(str[-3]) #output h print(str[-1]) #output n p y t h o n -6 -5 -4 -3 -2 -1

Strings String Slicing: A segment or a portion of a string is called as slice. Only required number of characters can be extracted from string using (:) symbol. The basic syntax of slicing a string: String_name[start : end : step] Where, s tart: the position from where it starts. e nd: the position where it stops(end – 1) s tep: also known as stride, is used to indicate number of steps to incremented after extracting first character. The default value of stride is 1.

Strings String slicing continued: If start is mentioned, it means that slice should start from the beginning of the string. If the end is not mentioned, it indicates the slice should be till end of the string. If both are not mentioned, it indicates the slice, should be from the beginning till the end of the string. For example: S = “abcdefghij” Character Index Reverse index a b c d e f g h i j 1 2 3 4 5 6 7 8 9 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Strings String slicing continued: Slicing Result Description S[2:5] cde Characters at indices 2,3,4 S[:5] abcde First five characters S[5:] fghij Characters at index 5 to the end S[-2:] ij Last two characters S[:] abcdefghij Entire string S[1:7:2] bdf Characters from index 1 to 6 by step 2 S[::-1] jihgfedcba A negative step reverses the string

String methods c apitalize() : Make the first character have upper case and the rest lower case. Example: str = “hello” print(str.capitalize()) Output: Hello f ind: This method return the location of the first string occurrence of the sub string from the main string. The find method return -1, if the substring is not found in the main string. The general form is: mainstring.find(substring, beg, end) For example: str = “hello” str1 = “hello world” print(str.find(“l”)) #output 2 print(str.find(“x”)) # returns -1 print(str1.find(“o”,6,9) # returns 6

String methods strip(): Return copy of the string with leading and trailing white spaces. For Example: str = “ hello world “ print(str.strip()) output: hello world strip(chars): If chars is given, remove characters specified at both the ends. For example: str = “ ### hello ###” print(str.strip(“#”)) output: hello r strip(): is to remove white spaces at right side. For Example: str = “hello “ print(str.rstrip()) output: hello

String methods l strip() : it is used to remove the white spaces at left side, For Example: str = “ hello” print(str.lstrip()) # output: hello c asefold(): It is an advanced version of lower() method. It converts the upper case letters to lower case letters including some special characters which are not specified in the ASCII table. For Example: str1 = “india” str2 = “INDIA” print(str1.casefold() == str2.casefold()) output: returns a value true s tartswith(): method returns true if the string starts with the specified value, Otherwise, false. General form is : string.startswith(value, start, end) Value: Required. The value to check if string starts with. Start: Optional. An integer specifying at which position to start the search. End: Optional. An integer specifying at which position to end the search

String methods For Example: str = “logical” print(str.startswith(“l”)) #returns true print(str.startswith(“g”)) # returns false print(str.startswith(“l”,2,5) # returns false j oin() : It is used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string. For Example: str1 = “-” str2 = “abc” print(str1.join(str2)) output: a-b-c s plit(): The split method is used to brake a string into pieces. These are returned as a list. For example: str = “one, two, three, four” str1 = str.split(“,”) print(str1) output: [ “one”, two”, ”three”, ”four”]

String methods l ower(): The lower method converts the capital letters into lowercase letters. For Example: str = “HELLO” print(str.lower()) # output hello u pper(): The upper method is used to convert all the characters of a string into uppercase. s wapcase(): This method is used to converts letters into lower case letters and vice versa. str = “python is f uture” print(str.swapcase()) output: PYTHON IS FUTURE title : The title method converts the string such that each word in the string starts with a capital letter and remaining will be lowercase letters. For Example: str = “python is future” print(str.title()) output: Python Is Future

String methods c ount(): This method is used to count the number of substrings occurs in a main string. str = “hello” print(str.count(“l”)) output : 2 r eplace(): This method is useful to replace a substring in a string with another sub string. The general form is: stringname.replace(old, new) for Example: str = “this is a beautiful college” str1 = “college” str2= “flower” str3 = str.replace(str1,str2) print(str3) output: this is a beautiful flower

String methods i salpha(): Returns true if the string has at least one character and all characters are alphabets(A to Z and a to z). Otherwise, it returns false. For example: str =“hello” print(str.isalpha()) output: True Note: Strings are immutable, an immutable object is object whose content cannot be changed. In python numbers, strings and tuple are immutable. Lists, sets, dictionaries are mutable objects.

Sorting strings We can sort a group of strings into alphabetical order using sort() method and sorted() function. When sort() method is used, it will sort the original array i.e. str. So the original order of strings will be lost and will have only one sorted array. To retain the original array even after sorting, we can use sorted() function. str1 = sorted(str) Here, str is the original array whose elements are to be sorted. After sorting the array, the sorted array will be referenced by str1. So, the sorted strings appear in str1. The original array ‘str’ is undistributed.

Sorting strings # python program to sort strings in alphabetical order str = [] # empty string n = int(input(“enter how many strings”)) print(“enter strings”) for i in range(n): str.append(input()) str1 = sorted(str) print(“sorted list”) for i in str1: print(i)

Lists A list is similar to an array that consists of a group of elements or items. The values inside the lists can be of any type like integers, float, strings and so on. The elements of the lists are enclosed within square brackets. Creating a list with numbers: l st = [10,20,30,40] Creating a list with strings: s = [“xxx”, “yyy”, “zzz”] Creating a list with different types: lst = [10,20,30,40.5,”xxx”] Nested lists can be created as follows: l1 =[10,20,30] l2 = [40.5, “xxx”] l3 = [ l1,l2]

Lists Creating a list using range function: 1. l1 = range(4) print(l1) Output: [0,1,2,3] 2. l1 = range(5,10) print(l1) output: [5,6,7,8,9] 3. l1 = range(5,10,2) print(l1) output: [5, 7, 9]

Lists Concatenation of lists: l1 = [10,20,30] l1 = l1 + [40,50] print(l1) Output: [10,20,30,40,50] Accessing the elements with in the inner list can be done by double indexing. For example: l = [ [10,20],[xxx, yyy]] print(l[1][0]) output: xxx

List slicing We can make a new list from a portion of an existing list using a technique known as slicing. A list slice is an expression of the form: list_name[begin: end: step] If the begin value is missing, it default to 0(zero) If the end value is missing, it default to the length of the list The default step value is 1. list index Reverse index 10 20 30 40 50 60 70 80 90 10 1 2 3 4 5 6 7 8 9 -10 -9 -8 -7 -6 -5 -4 -3- -2 -1

List slicing For example: lst = [10,20,30,40,50,60,70,80,90,100] print(lst) # output [10,20,30,40,50,60,70,80,90,100] print(lst[0:3]) # [output 10,20,30] print(lst[4:8]) # output [50,60,70,80] print(lst[-5:-3]) # output [60,70] print(lst[:3]) # output [10,20,30] print(lst[4:]) # output [50,60,70,80,90,100] print(lst[:]) # output [10,20,30,40,50,60,70,80,90,100] print(lst[-100:3]) #output [10,20,30] print(lst[4:100]) # output [50,60,70,80,90,100] print(lst[2:-2:2]) #output [30,50,70] print(lst[::2]) # output [10,30,50,70,90]

List slicing A begin value less than zero treated as zero. Ex: lst[-100:3] A end value greater than the length of the list is treated as the length of the list. Ex. Lst[4:100] # here 100 is treated as len(lst) Cloning of lists: x = [10,20,30,40] y = x[:] p rint(x) # output [10,20,30,40] p rint(y) # output [10,20,30,40]

Lists Built-in functions used on lists : There are several built-in functions that operate on lists. Here some useful functions. len – returns the number of items in the list s um – returns the sum of items in the list m in – returns the minimum in the list m ax – returns the maximum element in the list #program to demonstrate built-in functions lst = [30, 10, 50,40,20] print(“length =“, len(lst)) # output 5 print(“sum = “, sum(lst)) # output 150 print(“min =“, min(lst)) # output 10 print(“max =‘, max(lst)) #output 50

Methods to process lists Method Example Description Index() lst.index(x) Returns the first occurrence of x in the list append() lst.append(x) Appends x at the end of the list insert() lst.insert( i , x) Inserts x to the list in the position specified by i copy() lst.copy() Copies all the list elements into a new list and returns 1 extend() lst.extend(list1) Appends list1 to list count() lst.count(x) Returns the number of occurrences of x in the list remove() lst.remove(x) Removes x from the list pop() lst.pop() Removes the ending element from the list Sort() lst.sort() Sorts the elements of the list into ascending order reverse() lst.reverse() Reverses the sequence of elements from the list clear() lst.clear() Deletes all elements from the list

Lists # a python program to demonstrate list methods lst = [10, 20, 30, 40, 50] lst.append(60) print(“after appending 60 :”,lst) lst.insert(2,15) print(“list after inserting 15 at 2 nd position: ”,lst) lst1 = lst.copy() print(“newly created list1 : “, lst1) lst.extend(lst1) print(“list after appending list1 :”, lst) c = lst.count(50) print(“number of times 50 found in the list:”,c) lst.remove(50) print(“list after removing 50”,lst) lst.pop() print(“list after removing ending element:”, lst)

Lists # a python program to demonstrate list methods lst.sort() print(“list after sorting :”,lst) lst.reverse() print(“list after reversing:”, lst) lst.clear() print(“list after clearing all elements:”,lst ) For Example: lst.sort() :- This will sort list in ascending order. If we want to sort the elements of list into descending order, then we can mention reverse = “True” in the sort function. lst.sort(reverse = True)

Lists # python program to find the biggest element in the list lst = [] print(“how many elements”) n = int(input(“enter how many elements”)) print(“enter elements”) for i in range(n): lst.append(int(input()) print(“contents of list:”, lst) big = lst[0] for i in range(1,n): if lst[i] > big: big = lst[i] print(“biggest element = “, big)

Lists # Finding common elements in the list lst1 = [10,30,40,50,60] lst2 = [20,30,50,70] s1 = set(lst1) #converts list into set s2 = set(lst2) #converts list into set s3 = s1.intersection(s2) common = list(s3) # converting set to list print(common)

Sets A set in python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements. We use curly braces({}) to enclose the elements of the set. For example: s = {10,20,30,40} Set operation: s1 = {0,2,4,6,8} s2 = { 1,2,3,4,5} print(“union of s1 and s2 :”, s1 | s2) print (“intersection of s1 and s2 :”, s1 & s2 ) print (“difference of s1 and s2 :”, s1 - s2 ) print (“symmetric difference of s1 and s2 :”, s1 ^ s2)

Sets Operations on Sets: Operation Python syntax Meaning Union A | b Elements in A or B or both Intersection A & B Elements common to both A and B Set difference A – B Elements in A but not B Symmetric difference A ^ B Elements in A or B but not both

Tuple A tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the main difference is tuples immutable where as lists are mutable. Since tuples are immutable, once we create a tuple we cannot modify elements. Tuples are generally used to store data which should not be modified and retrieve that data on demand. Tuples are enclosed with the parenthesis: t = (10,20,30,40) t1 = (10,20,30.5,”xxx”) Accessing the tuple elements (slicing): t = (10,20,30,40,50) print(t[0]) # output 10 print(t[:]) # output (10,20,30,40,50) print(t[1:4]) # output is (20,30,40) print(t[::2]) # output is (10,30,50) print(t[::-2]) # output 50 30 10

Tuple Functions available to process tuples: Function/method Example Description len() len(t) Returns the number of elements in the tuple min() min(t) Returns the smallest element in the tuple max() max(t) Returns the biggest element in the tuple Count() t.count(x) Returns how many times the element x is found in tuple index() t.index() Returns the first occurrence of the element x in tuple. Raises value error if x is not found in the tuple. Sorted() sorted(t) Sorts the elements of the tuple into ascending order. sorted(t, reverse = true) will sort in reverse order

Dictionaries A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary, the first element is considered as key and the immediate next element is taken as its value. The key and value are separated by a colon(:). All the key key-value pairs in a dictionary are inserted in curly braces ({}). For Example: dict = {“id” : 123, “name”: “xxx”, “salary”:9000) key value key value key value # A python program to create a dictionary with employee details and # retrieve the values upon giving the key. dict = {“id” : 123, “name”: “xxx”, “salary”:9000 ) print(“id number =‘, dict[“id”]) print (“name = “, dict[“name”]) print (“salary = “, dict[“salary”])

Dictionaries Operations on Dictionaries: 1. If we want know how many key-value pairs are there in a dictionary, we can use the len() function. dict = {“id” : 123, “name”: “xxx”, “salary”: 9000} n = len(dict) print(“number of key-value pairs =“, n) #output 3 2. We can modify the existing value of a key by assigning a new value, as shown in the following statement. dict[“salary”] = 9500 3. We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key and assigning a value to it, as shown in the following statements. dict[“dept”] = “sports”

Dictionaries This pair is stored in the dictionary. If we print the dictionary created in the previous statement appears as shown below. print(dict) Output: {“id”:123, “dept”: “sports”, “name”: “xxx”, “salary”: 9500} Observe that “dept”: “sports” is added to the dictionary. Also, observe that this pair is not added at the end of the existing pairs. It may be added at any place in the dictionary. Suppose, we want to delete a key-value pair from the dictionary, we can use ‘del’ statement. del dict[“id”] This will delete the key “id” and its corresponding value from dictionary. Now, the dictionary look like this: {“dept”:”sports, ”name”: “xxx”, “salary” : 9500}

Dictionary methods Method Example Description clear() d.clear() Removes all key-value pairs from dictionary copy() d1 = d.copy() Copies all the elements from ‘d’ into a new dictionary ‘d1’ get() d.get( k[,v]) Returns the value associated with key ‘k’ items() d.Items() Returns an object that contains key-value pairs of ‘d’ keys() d.keys() Returns a sequence of keys from the dictionary d. values() d.values() Returns a sequence of values from the dictionary update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’

Dictionary # a python program to create a dictionary from keyboard and display the elements dict = {} # empty dictionary n = int(input(“how many key-value pairs”)) for i in range: print(“enter key”, end = “ “) k = input() # key is string print(“enter its value:”, end = “ “) v = int(input()) dict.update({k:v}) print(dict)

Files A file is a collection of related information stored on a disk permanently. Opening a file: To perform a operation on file, we must open a file. The general form of opening a file is. File handler = open(“filename”, ”open mode”) Here, ‘file name’ represents a name on which the data is stored . The file ‘open mode’ represents the purpose of opening file. The file opening modes: File open mode Description w To write data into a file. if any data is already present in the file, it would be deleted and present data will be stored. r To read data from the file. The file pointer is positioned at the beginning of the file

The file opening modes File open mode Description a To append data to the file, Appending means adding at the end of the existing file. The file pointer is placed at the end of the file. If file does not exists, it will create a new file for writing data. w+ To write and read data of a file. The previous data in the file will be deleted. r+ To read and write into a file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file. a+ To append and read data of a file. The file pointer will be at end of the file if the file exists, If file does not exists, it creates a new file for reading and writing. x To open a file in exclusive creation mode. The file creation fails if the file already exists.

Files For example: f = open(“abc.txt”, “w”) Here, ‘f’ represents the file handler or file object. It refers to the file with the name “abc.txt” that is opened in “w” mode. This means, we can write data into the file but we cannot read data from this file. If the file already exists, then its contents are deleted and the present data is stored into the file. Closing a file: A file which is opened should be closed using the close() method. Once a file is opened but not closed, then the data of the file may be corrupted or deleted in some cases. Also, if the file is not closed, the memory utilized by the file not freed, leading to problems like insufficient memory. This happens when we are working with several files simultaneously. Hence it is mandatory to close the file f.close()

Files # python program to create a file (write a data) and read data from the # file f = open(“abc.txt”, ”w”) str = input(“enter a text”) f.write(str) f.close() f = open(“abc.txt”, ”r”) str1 = f.read() print(str1) f.close()

Files # a python program to store a group of strings into a text file and # retrieve it. f = open(“xyz.txt”, ”w”) print(“enter text ( @ at end) : “) while str != “@”: str = input() if str != “@”: f.write(str + “\n”) f.close() f = open(“xyz.txt”, ”r”) print(“file contents”) str1 = f.read() print(str1) f.close()

Files # python program to count number of lines, words and characters in a # text f = open(“abc.txt”, “w”) print(“enter a text @ at end:”) while str != “@” str = input() if str != “@”: f.write(str + \n) f.close() f = open(“abc.txt”, “r”) cl = cw = cc = 0 for line in f: words = line.split() cl = cl + 1 cw = cw + len(words) cc = cc + len(line) print(“number of lines = “, cl) print(“number of words = “,cw) print(“number of characters =“,cc) f.close()

Class The mechanism that allows us to combine data and operations on those data into a single unit is called class. The general form of class is: A class is created with the keyword class and then writing the class name. The attributes are nothing but variables that contains data. __init__(self) is a special method or constructor to initialize the variables. Method1() and Method2() - - etc are methods that are intended to process the variables. class classname: attributes def __init__(self): def method1(): def method2():

class # python program to demonstrate class class Student: def __init__(self): self.usn = “ “ self.name = “ “ self.marks = 0 def getdata(self): self.usn = input(“enter usn”) self.name = input(“enter name”) self.marks = int(input(“enter marks”)) def putdata(self): print(“usn =“, self.usn) print(“name =“,self.name) print(“marks = “,self.marks) s = Student() # creating an object s.getdata() s.putdata()

Class Observe that the keyword class is used to declare a class. After this, we should write the class name. So student is our class name. Generally, a class name should start with a capital letter. Hence ‘s’ is capital in student. In the class, we write attributes and methods. To create an object, the following syntax is used: objectname = classname() So, to create an instance for object to the student class, we can write s = Student()

The self variable ‘self’ is a default variable that contains the memory address of the instance (object ) of the current class. So, we can use ‘self’ to refer to all the instance variable and instance methods. When an instance(object) to the class is created, the instance name contains the memory location of the instance(object). This memory location is internally passed to ‘self’. For example, we create an instance to student class as s = Student() Here s contains the address of the instance (object). This memory address is internally and by default passed to the ‘self’ variable. Since ‘self’ is known as the address of the instance(object). We use self in two ways. The ‘self’ variable is used as first parameter in the constructor as def __init__(self): In this case, self can be used to refer to the instance variables inside the construct0r

class ‘self’ can be used as first parameter in the instance method as, def getdata(self): Here, getdata() is instance method as it acts on the instance variables. Constructor: A constructor is a special method that is used to initialize the instance variables of a class. In the constructor, we create the instance variables and initialize them with some starting values. The first parameter of the constructor will be ‘self; variable that contains the memory address of the instance. For example def __init__(self): self.a = 0 self.b = 0 Here, the constructor has only one parameter, i.e. ‘self’. Using the ‘self.a’ and ‘self.b’, we can access the instance variables of the class. A constructor is called when we creating the object of a class.

Constrctors # python program to demonstrate a constructor class Cons: def __ init__(self): self.a = 10 self.b = 20 def printdata(self): print(self.a) print(self.b) x = Cons() x.printdata()

Parameterized Constructor class Parcons: def __init__(self, m = 0, n = 0): self.a = m self.b = n def putdata(self): print(self.a) print(self.b) x = Parcons() # constructor called without parameter y = Parcons(10,20) # constructor called with arguments x.putdata() y.putdata()

Polymorphism ‘Poly’ means ‘many’, morphism means forms. It is an ability to take more than one form. The polymorphism is achieved in python by using method overloading. Method Overloading ; If a method is written such that it can perform more than one task, it is called method overloading. # python program to demonstrate method overloading class Moverload: def add(self, m, n): self.c = m + n print( self.c ) m = Moverload() m.add(10,20) # output 30 m.add(“hello”, “world”) # output helloworld (concatenate two strings)

Constructor overloading # python program to overload a constructor class Coverload: def __init__(self, *args): for i in args: print(I, end = “ “) x = Coverload(10,20,30) # output 10 20 30 y = Coverload(“hello”, “world”) # output hello world

Inheritance The mechanism of deriving a new class from the old class is called inheritance. The old class is called base class and new class is called derived class. There are different types of inheritance. Single level inheritance Multi-level inheritance Hierarchical inheritance Multiple inheritance 1. Single Inheritance : A mechanism of deriving a single class from the base class is called single level inheritance.

Single Level Inheritance # Program to demonstrate single level inheritance class A: def __init__(self): self.a = 0 self.b = 0 self.c = 0 def getdata(self): self.a = int(input(“enter a”)) self.b = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b) class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) x = B() x.getdata() x.putdata() x.sum()

Multi-level Inheritance # Program to demonstrate multi level inheritance class A: def __init__(self): self.a = 0 self.b = 0 self.c = 0 def getdata(self): self.a = int(input(“enter a”)) self.a = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b)

Multi-Level Inheritance Continued class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) class C(B): # derived class def prod(self ): self.d = self.a * self.b print(self.d) x = C() x.getdata() x.putdata() x.sum() x.prod()

Hierarchical Inheritance # python program to implement Hierarchical inheritance class A: def __init__(self): self.a = self.b = 0 def getdata(self): self.a = int(input(“enter a”)) self.b = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b)

Hierarchical Inheritance continued class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) class C (A): # derived class def prod(self): self.d = self.a * self.b print(self.d) x = B() x.getdata() x.putdata() x.sum () y = C () y.getdata () y.putdata () y.prod()

Multiple Inheritance # python program to implement Multiple inheritance class A: def __init__(self): self.a = def getdata(self ): self.a = int(input(“enter a”)) class B: def __init__(self): self.b = 0 def inputdata(self ): self.b = int(input(“enter b”))

Multiple Inheritance continued class C(A,B): def sum(self): self.s = self.a + self.b print(self.s) x = C() x.getdata() x.inputdata() x.sum()

Method Overriding When there is a method in the super class, Writing the same method in the sub class so that it replaces the super class method is called method overriding. # Python program to demonstrate method overriding class A: def disp(self): print(“welcome to java world”) class B(A): def disp(self): print(“welcome to Python world”) x = B() x.disp() # output is welcome to python world

Constructors in super class class A: def __init__(self): print(“super class constructor executed”) class B(A): def __init__(self): print(“sub class constructor called”) x = B() output: sub class constructor executed. If you have constructor written in the super class and subclass, then it will execute sub class constructor. If you do not have a sub class constructor, then it will execute the super class constructor.

Module 3 Regular Expression: A regular expression is a string that contains special symbols and characters to find and extract the information needed by us from the given data. A regular expression helps us to search information, match, find and split information as per our requirements. Sequence characters in regular expressions Character Its Description \d Represents any digit ( 0 to 9) \D Represents any non digit \s Represents white space \S Represents non white space \w Represents any alphanumeric (A to Z, a to z, 0 to 9) \W Represents non-alphanumeric \b Represents a space around words \A Matches only at start of the string

Regular Expressions Regular expression are used to perform the following important operations. Python provides ‘re’ module that stands for regular expression. This module contains the following methods. Matching strings Searching for strings Finding all strings Splitting string into pieces Replacing strings m atch method() : The match method searches the beginning of the string and if matching string is found, it returns an object that contains the resultant string. Otherwise it returns the none. We can access the string from the returned object using group() method.

Regular Expressions # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “man, sun, mop, run” result = re.match(r “m\w\w”, str) print(result.group()) output: man . # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters . import re str = “sun, man, mop, run” result = re.match(r “m\w\w”, str) print(result) output: none

Regular Expressions findall() : Method searches the string from beginning till the end and returns all occurrences of the matching string in the form of list object. If the matching strings are not found , then it returns empty list # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “man, sun, mop, run” result = re.findall(r “m\w\w”, str) print(result) Output: [“man”, “mop”]

Regular Expressions search(): The search method searches the string from beginning till the end returns the first occurrence of the matching string. Otherwise, it returns none. We can use group() method to retrieve the string from the object returned by this method. # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “ sun, man, mop, run” result = re.findall(r “m\w\w”, str) print(result) Output: man

Regular Expressions s plit(): The split() method splits the string according to the regular expression and resultant pieces returned as a list. If there are no string pieces, then it returns an empty list. # A python program to create a regular expression to split string into pieces where one or more white spaces. import re str = “welcome to python” result = re.split(“ \s+”, str) print(str) Output: [“welcome”, “to”, “python”]

Regular Expressions s ub(): This method substitutes or replaces in the place existing strings. After substitution, the main string is returned by this method. import re str = “welcome to java” res = re.sub(r “welcome”, “python”,str) print(res)

Module 4 Arrays and Numpy in Python : An array is an object that stores group of elements of same datatype Advantages of Arrays: Arrays are similar to lists. The main difference is that always can store only o ne type of elements. Where as the lists can store different types of elements. The size of the array is not fixed in python. Hence, we need not specify how many elements we are going to store into array in the beginning. Arrays can grow or shrink in memory dynamically(during run time) Methods that are useful to process the elements of any array are available in array module.

Arrays Creating an array : The type should be specified by using a type code at the time creating the array object as: a rrayname = array(typecode, [elements]) The typecode ‘i’ represents I integer type where we can store integer numbers. If the type code is ‘f’ then it represents float type array where we can store numbers with decimal point. The important type codes are given below: Typecode Ctype Minimum size in bytes ‘b’ Signed integer 1 ‘B’ Unsigned integer 1 ‘i’ Signed integer 2 ‘I’ Unsigned integer 2 ‘l’ Signed integer 4 ‘L’ Unsigned integer 4 ‘f’ Double precision floating point 4

Arrays Type code Ctype Minimum size in bytes ‘d’ Double precision floating point 8 ‘u’ Unicode character 2

Arrays # creating an array using python import array as ar a = ar.array(“i”, [-1,2,3,4]) print(“elements of array”) for i in a: print(i) Output: -1 2 3 4

Arrays # Creating array with characters import array as ar a = ar.array(‘u’,[‘a’, ‘b’, ‘c’, ‘d’]) print(“the array elements are”) for ch in a: print(ch) # output a b c d # Creating floating type array import array as ar a = ar.array (‘f ’,[1.5,2.5,3.5.4.5]) print(“the array elements are”) for i in a: print(i) # output 1.5 2.5 3.5 4.5

Arrays # A python program to retrieve the elements of an array using index import array as ar a = ar.array(‘I’, [10,20,30,40]) n = len(a) for I in range(n): print(a[i], end= “”) # output 10 20 30 40

Array Slicing A slice presents a piece of the array. When we perform slicing operation on any array, we can retrieve a piece of the array that contains a group of elements. The general format of slice is: arrayname[start : stop : step] import array as ar a = ar.array(‘i’, [10,20,30,40,50]) print(a[1:4]) # output [20,30,40] print(a[0:]) # output print all the elements of an array print(a[:4] # output [10,20,30,40] print(a[-4:]) # prints the last four elements [20,30,40,50] print(a[-4: -1] # prints [20,30,40] print(a[0:4:2]) # prints [10,30]

Processing the arrays The arrays class of arrays module in python offers methods to process the arrays easily. The programmers can easily perform certain operations by using these methods. Method Description a.append(x) Adds an element ‘x’ at the end of the existing ‘a’ a.count(x) Returns the number of occurrences of x in the array ‘a’ a.extend(x) Appends x at the end of the array a . ‘x’ Can be another array a.fromfile(f, n) Reads n items from the file object a.fromlist(lst) Appends items from the list to the end of the array. a.fromstring(s) Appends items from the string ‘s’ to the end of the array ‘a’ a.Index(x) Inserts the position of the first occurrence of x in the array

Processing the arrays Method Description a.Insert(i, x) Inserts ‘x’ in the position ‘I’ a.pop() Removes the last item from the array ‘a’. a.remove(x) Removes the first occurrence of x in the array ‘a’ a.reverse() Reverses the order of elements in the array ‘a’ a.tolist() Converts the array ‘a’ into list

Program to demonstrate array methods import array as ar a = ar.array(‘i’, [10, 20, 30, 40, 50]) a.append(60) print(a) # output [10,20,30,40,50,60] a.insert(2,70) print(a) # output [10,20,70,30,40,50,60] a.remove(20) print(a) # output [10,70,30,40,50,60] a.pop() print(a) # output [10,70,30,40,50] print(a.index(30)) # returns 2 lst = a.tolist() print(lst) # output [10,70,30,40,50]

Program to read and print an array using keyboard import array as ar a = ar.array(‘i’, []) # creates an empty array to store integers n = int(input(“enter how many elements”)) for i in range(n): print(“enter an element”) a.append(int(input()) print(“the contents of array”) for i in a: print(i)

Numpy Numpy is a package that contains several classes, functions, variable etc, to deal with scientific calculations in python. Numpy is useful to create and also process single and multi-dimensional arrays. In addition, numpy contains a large library of mathematical functions like linear algebra functions and Fourier transformations. Creating array using numpy : import numpy as np a = np.array([10,20,30,40],int) print(a) Creating arrays in numpy can be done in several ways. Some of the important ways are

Numpy Creating arrays in numpy can be done in several ways. Some of the important ways are: Using array() function Using linspace() function Using logspace() function Using arange() function Using zeros() and ones() function Creating array using array() We can call array function of numpy module to create an array. When create an array, we can specify the datatype of the elements either ‘int’ or ‘float’. We can create an integer array type array as arr = array([10,20,30,40],int)

Numpy To create an array with float type elements, we should specify ‘float’. Import numpy as np arr = np.array ([10.5,20.5,30.5.40.5], float) In the array, if python interpreter finds one element belonging to ’float type’, then it will also convert into float type by a decimal point after the element as Import numpy as np arr = np.array ([10,20,30.5,40]) If we display this array using print() function, we can see the array as [ 10., 20., 30.5, 40.] To create an array with character type elements, we need not specify the datatype. We can simply write import numpy as np arr = np.array ([‘a’, ’b’ ,’c’, ‘d’])

Numpy # creating a array using numpy import numpy as np a = np.array([10,20,30,40],int) print(a) Creating arrays using linspace: The linspace() function is used to create an array with evenly spaced points between a starting and ending point. The general form of the linspace() function as: linspace(start, stop, n) ‘start’ represents the starting element and stop represents the ending element. ‘n’ is an integer that represents the number of parts the elements should be divided. If ‘n’ is omitted, then it is taken as 50.

Numpy # a python program to creating an array with 5 equal parts using linspace. import numpy as np a = np.linspace(2,10,5) print(“a = “,a) Output: a = [2,4,6,8,10] Creating arrays using logspace: The linspace() function produces evenly spaced points. Similarly, logspace() function produces evenly spaced points on a logarithmically spaced scale. The general form is: logspace(start, stop, n) The logspace() function starts at value which is ‘start’ to the power of 10 and ends at a value which is stop to the power of 10. If n is not specified, then its value is taken as 50. For example: if we write

Numpy a = logspace(1,4,5) The function represents values 1 to the power of 10 to 4 to the power of 10. These values are divided into 5 equal points and those points are stored into the array ‘a’. import numpy as np a = np.logspace(1,4,5) print(a) Output: [10.0, 56.2,316.2, 1778.3,10000.0] Creating arrays using arange() function The arange() function in numpy as same as range() function in python. The arange function is used in the following format. arange(start, stop, stepsize) This creates an array with a group of elements from start to stop – 1 in steps of step size. If the step size is omitted, then it is taken as zero. Ex : arange(10) will produce an array with elements 0 to 9. arange(5,10) will produce an array with elements from 5 to 9 arange(1,10,3) will produce 1, 4, 7 arange(5,1,-1) will produce 5,4,3,2

Numpy # Creating array with arange function import numpy as np a = np.arange(2,11,2) print(“a =“, a) Output: a = [2,4,6,8,10] Creating arrays using zeros() and ones() function: We can use zeros() functions to create an array with all zeros. The one function is useful to create an array with all 1’s. They are written in the following format. zeros(n, datatype) ones(n, datatype) Where ‘n’ represents the number of elements. We can eliminate the ‘datatype’ argument. If we do not specify the datatype then the default datatype used by numpy as ‘float’.

Numpy For example: zeros(4) This will create an array with four elements all zeros as [0.,0.,0.,0.] If we want this array in integer format, we can use ‘int’ as datatype, as zeros(4,int) this will create an array as : [0,0,0,0] If we use ones() function, it will create an array with elements 1. For ex: ones(5,float) will create an array with 5 integer elements are [1.,1., 1.,1.,1.] Creating arrays using zeros() and ones() import numpy as np a = np.zeros(5,int) print(a) b = np.ones(5) # default datatype is float print(b)

Numpy We apply mathematical functions like sin(), cos(), sqrt(), e xp() and so on the elements of the array. The list of functions that can be used on numpy arrays. Function meaning sin(arr) Calculate the sine value of each element in the array arr. cos(arr) Calculates the cosine value of each element in the array arr. log(arr) Calculates natural logarithmic value of each element in the array arr. abs(arr) Calculates absolute value of each element in the array arr. sqrt(arr) Calculates square root value of each element in the array arr. pow(arr,n) Returns power value of each element in the array ‘arr’ when raised to the power of n.

Numpy Function Meaning exp(arr) Calculates exponentiation value of each element in the array arr. sum(arr) Returns the sum of all elements in the array arr. prod(arr) Returns the product of all the elements in the array arr. min() Returns smallest element in the array arr. max(arr) Returns the biggest element in the array arr. mean(arr) Returns the mean value( average ) of elements in the array arr. median(arr) Returns median value of all elements in the array arr. unique(arr) Gives array that contains unique elements of the array arr. sort(arr) Gives an array with sorted elements of the array arr in ascending order

Numpy # python program to demonstrate mathematical function on arrays. import numpy as np arr = np. a rray([10,20,30,5,40],int) print(“original array = “, arr) print(“after adding 5 = “, arr + 5) print(“sin value = “, sin(arr)) print(“cos value =“, cos(arr)) print(“biggest value =“, max(arr)) print(“minimum value = “, min(arr)) print(“sum of all elements = “, sum(arr)) print(average of all elements = “,avg(arr))

Numpy Comparing Arrays : We can use the relational operators >,<,==, >=,<=,>=, and != to compare the arrays of same size. import numpy as np a = np.array([1,2,3,0],int) b = np.array([0,2,3,1],int) c = a== b print(“result of a==b”, c) c = a > b print(“result of a >b”, c) c = a <= b print(“result of a<=b”, c) Result of a==b [False True True False] Result of a>b [True False False False] Result of a<=b [False True True True]

Numpy a ny() Function : The any function can be used to determine if any one element of the array is True. a ll() Function: The all() function can be used to determine whether the all elements in the array are true. The any() and all() functions returns either True or False. # python program to demonstrate all() any() functions. import numpy as np a = np.array([1,2,3,0 ],int) b = np.array([ 0,2,3,1],int) c = np.array([0,2,3,1],int) d = a > b print (“check if any one of the element is true”, any(d)) d = b == c print (“check if all elements are true”, all(d)) Output: True True

Slicing in Numpy arrays import numpy as np a = np.arrange(1,6) # creates an array an array with 1 to 5 print(a) # prints 1 2 3 4 5 b = a[1:6:2] print(b) # prints [1,3,5] b = a[-2,2:1] print(b) # prints[4,3,2 ] b = a[: -2 : ] print(b) # prints [1,2,3]

Attributes of numpy array (variables) Numpy array class is called ndarray. This class contains the following attributes. The ‘ndim’ attribute : The ‘ndim’ attribute represents the number of dimensions of the array. The number of dimensions is also referred to as rank. For a single dimensional array rank is 1 and for two dimensional array brank is 2. # program to demonstrate ndim attribute import numpy as np a = np.array([1,2,3,4],int) print(a.ndim) # returns 1 b = np.array ([[1,2,3],[4,5,6]],int) print(b.ndim ) # returns 2 The ‘shape’ atttribute: The ‘shape’ attribute gives the shape of an array. The shape is tuple listing the number of elements along each dimension. For a 1 dimensional array, shape elements in the row. For a two dimensional array, it specifies the number of rows and columns in each row. We can also change the shape using ‘shape’ attribute.

Attributes of numpy array (variables) # program to demonstrate shape attribute a = np.array([1,2,3,4],int) print(a.shape) # prints (4,) b = np.array([[1,2,3],[4,5,6]],int) print(b.shape) # prints (2,3) b.shape = (3,2) print(b) # [[1 2] [3 4] [5 6]]

Attributes of numpy array (variables) The size attribute : The ‘size’ attribute gives the total number of elements in the array. # Python program to demonstrate size attribute. import numpy as np a = np.array([1,2,3,4,5],int) # prints 5 print(a.size) b = np.array([[1,2,3], [4,5,6]],int) print(b.size) # prints 6 The ‘itemsize’ attribute : The ‘item size’ attribute gives the memory size of the array element in bytes import numpy as np a = np.array([1,2,3,4],int) print(a.size) # prints 4 (long integer) b = np.array([1.5,2.5,3.5,4.5],float) # prints 8 (double precision)

Attributes of numpy array (variables) The dtype attribute : The ‘dtype’ attribute gives the datatype of the elements in the array. import numpy as np a = np.array([1,2,3,4],int) print(a.dtype) # prints int32 b = np.array([1.5,2.5,3.5.4.5],float) print(b.type) # pints float64 The nbytes attribute: The ‘nbyte’ attribute gives the total number of bytes occupied by an array. The total number of bytes = size of array * itemsize of each element in the array.

Attributes of numpy array (variables ) # Python program to demonstrate nbytes attribute import numpy as np a = np.array([1,2,3,4],int) print(a.nbytes) # prints 16 each element occupies 4 bytes b = np.array([[1,2,3],[4,5,6]],int) print(b.nbytes) # prints 24 bytes c = np.array([1.5,2.5.3.5,4.5],int) print(c.nbytes) # prints 32 bytes

Numpy The reshape() method : The reshape() method is useful to change the shape of an array. The new array should have the same number of elements as in the original array. # Pyhton program to demonstrate reshape() method import numpy as np a = np.arange (6 ) print(a) # creates an array [0,1,2,3,4,5] b = np.reshape(2,3) print(b) # change the shape as 2 rows and 3 columns output: [[0 1 2], [3,4,5]]

Numpy The flatten method: The flatten method is useful to return a copy of the array collapsed into one dimension. # Python program to demonstrate flatten method a = np.array([[1,2,3],[4,5,6 ],int) print(a) # [[ 1 2 3] [ 4 5 6]] b = a.flatten() print(b) # prints [1 2 3 4 5 6]

Working with multidimensional arrays with numpy The 2d array, 3D arrays , etc . Are called multidimensional arrays. A 2D array contains more than 1 row and 1 column. A 2D array is also considered as matrix. For Ex: A 2D array with m rows and n columns is called m * n matrix. We can create multidimensional arrays in the following ways. Using array Function. Using ones() and zeros() function Using eye() function Using reshape() function The array() Function: Numpy’s array function can be used to create multidimensional array. Usually, we pass lists of elements to this function.

Working with multidimensional arrays with numpy # python program to create a multidimensional array. import numpy as np a = np.array([[1,2,3], [4,5,6]]) print(a) Output:[[1 2 3] [4 5 6]] The ones() and zeros() functions : The ones() function is useful to create a 2D array with several rows and columns where all the elements will be taken as 1. The format of this function is: ones ((r, c),datatype) Here ;r; represents number of rows and ‘c’ represents the number of columns. Datatype represents the datatype of the elements in the array.

Working with multidimensional arrays with numpy # python program to demonstrate ones() function to create array import numpy as np a = np.one((2,2),float) print(a) Output: [[ 1. 1.] [1. 1.]] Just like the ones() function, we can also use the zeros() function to create a 2d array with elements filled with zeros. # python program demonstrate zeros() to create array import numpy as np a = np.zeros((2,2),int) print(a) Output: [[0 0] [0 0]]

Working with multidimensional arrays with numpy The eye() function : The eye() function creates a 2d array and fills the elements in the diagonal with 1’s. The general format of using this function is: eye(n, dtype = datatype) This will create an array with ‘n’ rows and ‘n’ columns. The default datatype float. # Python program to demonstrate eye function import numpy as np a = np.eye(2) print(a) # out put [[1. 0.] [0. 1.]] b = np.eye(2, dtype = int) print(b) # output [[ 1 0] 0 1]]

Working with multidimensional arrays with numpy The reshape() function: This function is useful to convert 1D array into multidimensional array. The general form is: reshape(arrayname,(n, r, c)) Here, array represents the name the array whose elements to be converted . ‘n’ indicates the number the number of arrays in the resultant array. ‘r’, ‘c’ indicates the number of rows and columns respectively. # program to demonstrate reshape() function import numpy as np a = np.array([1,2,3,4,5,6]) b = np.reshape(a,(2,3)) print(b) # output [[1 2 3] [4 5 6]]

M atrices in numpy In, mathematics, a matrix represents a rectangular array of elements arranged in rows and columns. When a matrix has more than 1 row and more than 1 column, it is called m * n matrix. Where m represents the rows and n represents the columns. # create a matrix import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = np.matrix(a) print(b) # output [[1 2 3] [4 5 6]]

Getting Diagonal elements of a matrix To retrieve the diagonal elements of a matrix, we can use diagonal () function: The general for is: a = diagonal(matrix) The diagonal() function returns a 1D array that contains diagonal elements of the original matrix. import numpy as np a = np.matrix(‘1 2 3; 4 5 6; 7 8 9’) print(a) # output [[ 1 2 3] [4 5 6] [7 8 9]] d = np.diagonal(a) print(d) # output [ 1 5 9]

Finding maximum and minimum elements To know the maximum element, we use max() method and to the minimum element, we can use min() method. These methods should be using matrix name. # program to demonstrate max(0 and min() method import numpy as np a = np.array([[3,1,2],[8,4,6]]) b = np.matrix(a) big = b.max() small = b.min() print(big) print(small)

Finding sum and average of elements To find the sum of all elements in the matrix, we can use sum() method and to find average, we can use mean method. These methods should be called using the matrix name. import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = np.matrix(a) s = b.sum() m = b.mean() print(s) # output 21 print(m) # output 3.5

Product of elements It is possible to know the product of elements in a matrix. For this purpose, numpy provides prod() method. For example: prod(0) returns a matrix that contains the products of elements in each column of the original matrix. p rod(1) returns a matrix that contains products of elements of each row. These methods should be called using matrix name. # Python program to demonstrate product() a = np.array([[1,2],[3,4]]) # [1 2 3 4] b = np.matrix(a) c = b.prod(0) print(c) # [3 8] r = b.prod(1) print(r) # [[2] [12]]

Sorting the matrix Numpy provides sort function that sorts the matrix elements into ascending order. The general syntax is: sort(matrixname, axis) If we use axis = 1, it sorts the elements in each into ascending order. If we use axis = 0, then it sorts the elements in column into ascending order. The default value of axis is 1. # program to demonstrate sort method import numpy as np a = np.array([[3,5,4],[1,8,6]]) # 3 5 4 1 8 6 b = np.matrix(a) r = np.sort(b,1) print(r) # output [[ 3 5 4] [1 6 8]] c = np.sort(b,0) # output [ [1 5 4] [3 8 6]]

Transpose a matrix Rewriting matrix rows and into columns and vice versa is called ‘transpose’. Thus the rows in the original matrix will become rows in the original matrix will become rows in the transpose matrix. To find the transpose, we can transpose() and getT() methods in numpy. These methods should be called using matrix name. # Python program to demonstrate transpose method import numpy as np m = np.matrix(‘1,2; 3,4; 5,6’) print(m) # output [[ 1 2] [3 4] [5 6] t = m.transpose () t1 = m.getT() # output [[ 1 3 5] print(t1) [ 2 4 6]]

Matrix addition and Multiplication # python program demonstrate arithmetic operations import numpy as np a = np.matrix([[1,2].[3,4]]) a = [ 1 2 3 4] b = np.matrix([[1,2].[3,4 ]]) b = [1 2 3 4] c = a + b print(c) # output [ [2 4] [6 8]] d = a – b #output [[0 0] [0 0]] print(d) e = a * b # output [[7 10] [15 12]] print(e)
Tags