0% found this document useful (0 votes)
1 views99 pages

PythonUnit2

Unit II of the Introduction to Python Programming covers various operators in Python, including arithmetic, assignment, unary, relational, logical, boolean, bitwise, membership, and identity operators. It explains how these operators function, their precedence, and provides examples for clarity. Additionally, it touches on operator precedence and associativity, as well as the use of built-in mathematical functions.

Uploaded by

veena more
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views99 pages

PythonUnit2

Unit II of the Introduction to Python Programming covers various operators in Python, including arithmetic, assignment, unary, relational, logical, boolean, bitwise, membership, and identity operators. It explains how these operators function, their precedence, and provides examples for clarity. Additionally, it touches on operator precedence and associativity, as well as the use of built-in mathematical functions.

Uploaded by

veena more
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 99

INTRODUCTION TO PYTHON PROGRAMMING Unit II

UNIT-II
CHAPTER-1
OPERATORS IN PYTHON:
An operator is a symbol that performs an operation. An operator acts on
some variables called operands. For example, if we write a + b, the operator ‘+’
is acting on two operands ‘a' and 'b'. If an operator acts on a single variable, it
is called unary operator. If an operator acts on two variables, it is called binary
operator. If an operator acts on three variables, then it is called ternary
operator.
Classification of operators is given below:
 Arithmetic Operators
 Assignment Operators
 Unary Minus Operators
 Relational Operators
 Logical Operators
 Boolean Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

 ARITHMETIC OPERATORS
These operators are used to perform basic arithmetic operations like
addition, subtraction, division, etc.

There are seven arithmetic operators available in Python. Since these


operators act on two operands, they are called ‘binary operators’ also.
Let's assume a = 13 and b=5

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 1


INTRODUCTION TO PYTHON PROGRAMMING Unit II

When there is an expression that contains several arithmetic operators, we


should know which operation is done first and which operation is done next.
In such cases, the following order of evaluation is used:

1. First parentheses are evaluated.

2. Exponentiation is done next.

3. Multiplication, division, modulus and floor divisions are at equal priority.

4. Addition and subtraction are done afterwards.

5. Finally, assignment operation is performed.

Let's take a sample expression: d = (x+y)*z**a//b+c.


Assume the values of variables as: x=1; y=2; z=3; a=2; b=2; c=3.
Then, the given expression d = (1+2)*3**2//2+3 will evaluate as:

1. First parentheses are evaluated. d = 3*3**2//2+3.

2. Exponentiation is done next. d = 3*9//2+3.

3. Multiplication, division, modulus and floor divisions are at equal priority.

d =27//2+3 and then d = 13+3.

4. Addition and subtraction are done afterwards. d = 16.

5. Finally, assignment is performed. The value 16 is now stored into 'd'.

Hence, the total value of the expression becomes 16 which is stored in the variable 'd'.

ASSIGNMENT OPERATORS

These operators are useful to store the right side value into a left side variable.
They can also be used to perform simple arithmetic operations like addition,
subtraction, etc., and then store the result into a variable. Python does not
have increment operator(++) and decrement operator(--) that are available in C and
Java. These operators are shown in Table.
Let's assume the values x = 20, y=10 and z = 5

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 2


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Example: a=b=1
print(a,b) # will display 1 1

UNARY MINUS OPERATORS


The unary minus operator is denoted by the symbol minus (-). When this
operator is used before a variable, its value is negated. That means if the variable
value is positive, it will be converted into negative and vice versa.
Example: n = 10
print (-n) # displays -10

num=-10
num = -num
print (num) # displays 10

RELATIONAL OPERATORS
Relational operators are used to compare two quantities. We can
understand whether two values are same or which one is bigger or which one
is lesser, etc. These operators will result in True or False depending on the
values compared, as shown in Table.We are assuming a = 1 and b = 2.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 3
INTRODUCTION TO PYTHON PROGRAMMING Unit II

Example: a=1;b=2
if(a>b):
print(“Yes”)
else:
print(“No”)

LOGICAL OPERATORS
Logical operators are useful to construct compound conditions. A
compound condition is a combination of more than one simple condition. Each
of the simple condition evaluated to True or False and then the decision is
taken to know whether the total condition is True or False. Let's take x = 1 and
y=2 in this table.

x=1; y=2; z=3;


if (x<y and y<z):
print(‘Yes’)
else
print(‘No’)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 4


INTRODUCTION TO PYTHON PROGRAMMING Unit II

In the above statement, observe the compound condition after if. That is x
<y and y<z. This is a combination of two simple conditions, x<y and y<z.
When ‘and' is used, the total condition will become True only if both the
conditions are True. Since both the conditions became True, we will get
'Yes' as output

BOOLEAN OPERATORS
There are two ‘bool' type literals. They are True and False. Boolean
operators act upon ‘bool' type literals and they provide ‘bool' type output. There
are three Boolean operators as mentioned in Table Let's take x = True and y =
False.

BITWISE OPERATORS
These operators act on individual bits (0 and 1) of the operands. When
we use these operators on integers, these numbers are converted into bits
(binary number system) and then bitwise operators act upon those bits. The
results given by these operators are always in the form of integers.

Example 1: Converting 45 into binary number system.


Rule: Divide the number successively by 2 and take the remainders from
bottom to top, as shown in Figure 4.3. The decimal number 45 is represented
as 101101 in binary. If we use 8 bit representation, we can write it as: 0010
1101.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 5


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Example 2: Converting binary number 0010 1101 into decimal number.


Rule: Multiply the individual bits by the powers of 2 and take the sum of the
products. Here, the sum is coming to 45. So 0010 1101 in binary is equal to 45
in decimal number system.

There are 6 types of bitwise operators as shown below:


i)Bitwise Complement operator (~ )
ii)Bitwise AND operator (&)
iii)Bitwise ORoperator (1)
iv)Bitwise XOR operator (^)
v)Bitwise Left shift operator (<<)
vi)Bitwise Right shift operator (>>)

i)Bitwise Complement Operator (~)


This operator gives the complement form of a given number. This operator
symbol is which is pronounced as tilde. Complement form of a positive
number can be obtained changing O's as 1's and vice versa. The complement
operation is performed by NOT gate circuit in electronics.The truth table is
given for NOT gate as shown below.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 6


INTRODUCTION TO PYTHON PROGRAMMING Unit II

If x= 10, find the ~x value.


x = 10 = 0000 1010.

By changing O's as 1's and vice versa, we get 1111 0101. This is nothing but -
11 (in decimal). So, ~x = -11.

ii)Bitwise AND Operator (&)


This operator performs AND operation on the individual bits of
numbers. The symbol for this operator is & which is called ampersand.
Bitwise AND operator given in table.

From the truth table, we can conclude that by multiplying the input bits, we
can get output bit. The AND gate circuit present in the computer chip will
perform the operation.

If x= 10, y = 11. Find the value of x&y.


x = 10=0000 1010.
y = 11=0000 1011.
From the truth table, by multiplying the bits, we can get x&y=0000 1010. This
is nothing but 10 (in decimal).

iii)Bitwise OR Operator (|)


This operator performs OR operation on the bits of the numbers.
The symbol of bitwise OR operator is |, which is called pipe symbol. To
understand this operation, see the truth table.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 7


INTRODUCTION TO PYTHON PROGRAMMING Unit II

If x= 10, y = 11, find the value of x|y.


x = 10 = 0000 1010.
y = 11 = 0000 1011.

The truth table shows that by adding the bits, we can get x|y=0000 1011. This
is nothing but 11 (in decimal).

iv)Bitwise XOR Operator (^)


This operator performs exclusive or (XOR) operation on the bits of
numbers. The symbol is ^, which is called cap, carat, or circumflex symbol.
From the table, we can conclude that when we have odd number of 1's in the
input bits, we can get the output bit as 1.

If x= 10, y = 11, find the value of x^y.


x = 10 = 0000 1010.
y = 11 = 0000 1011.

From the truth table, when odd number of 1's are there, we can get a 1 in the output .
Thus, x^y = 0000 0001 is nothing but 1 (in decimal).

v)Bitwise Left Shift Operator (<<)


This operator shifts the bits of the number towards left a specified number of
positions. The symbol for this operator is <<, read as double less than. If we write
x<<n, the meaning is to shift the bits of x towards left n positions.

If x= 10, calculate x value if we write x<<2

Shifting the value of x towards left 2 positions will make the leftmost 2 bits to be lost.
The value of x is 10 = 0000 1010. Now, x<<2 will be 0010 1000 = 40 (in decimal).

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 8


INTRODUCTION TO PYTHON PROGRAMMING Unit II

vi)Bitwise Right Shift Operator (>>)


This operator shifts the bits of the number towards right a specified number of
positions. The symbol for this operator is >>, read as double greater than. If we write
x>>n, the meaning is to shift the bits of x towards right n positions.

>> shifts the bits towards right and also preserves the sign bit, which is the
leftmost bit. Sign bit represents the sign of the number. Sign bit 0 represents a
positive number and 1 represents a negative number. So, after performing >>
operation on a positive number, we get a positive value in the result also. If right
shifting is done on a negative number, again we get a negative value only.
If x= 10, then calculate x>>2 value

Shifting the value of x towards right 2 positions will make the rightmost 2 bits to be
lost. x value is 10 = 0000 1010. Now x>>2 will be: 0000 0010 = 2 (in decimal)

MEMBERSHIP OPERATORS
The membership operators are useful to test for membership in a sequence
such strings, lists, tuples or dictionaries. For example, if an element is found in the
sequence or not can be asserted using these operators. There are two membership
operators as shown here:
i)in
ii)not in

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 9


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The in Operator
This operator returns True if an element is found in the specified sequence. If the
element is not found in the sequence, then it returns False.
Ex: x = ["apple", "banana"]
print("banana" in x) #display true

The not in Operator


This works in reverse manner for 'in' operator. This operator returns True if an
element is not found in the sequence. If the element is found, then it returns False.
Ex: x = ["apple", "banana"]
print("pineapple" not in x) #display true

IDENTITY OPERATORS
These operators compare the memory locations of two objects. Hence, it is
possible to know whether the two objects are same or not.
There are two identity operators:
i)is
ii)is not

i)is
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.
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z) # returns True because z is the same object as x
print(x is y) # returns False because x is not the same object as y, even if
they have the same content
print(x == y) # to demonstrate the difference betweeen "is" and "==": this
comparison returns True because x is equal to y

ii)is not
This is not operator returns True, if the identity numbers of two objects being
compared are not same. If they are same, then it will return false.
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 10


INTRODUCTION TO PYTHON PROGRAMMING Unit II

z=x
print(x is not z) # returns False because z is the same object as x
print(x is not y) # returns True because x is not the same object as y, even if they
have the same content
print(x != y) # to demonstrate the difference betweeen "is not" and "!=": this
comparison returns False because x is equal to y

OPERATOR PRECEDENCE & ASSOCIATIVITY


An expression or formula may contain several operators. In such a case,
the programmer should know which operator is executed first and which one
is executed next. The sequence of execution of the operators is called operator
precedence.
Precedence represents the priority level of the operator. The operators
with higher precedence will be executed first than of lower precedence.

Suppose an expression contains operators having same


precedence,then which operator is executed first is another question. It means
knowing whether the execution is from left to right or right to left. This is
called associativity. 'Associativity' is the order in which expression is
evaluated that has multiple operators of the same precedence. Almost all the
operators have left-to-right associativity in Python.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 11


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Let's take an 3/2*4+3+(10/4)**3-2 to understand how these


precedence rules can be applied. The final value of this expression will be
22.625, as shown in Table

MATHEMATICAL FUNCTIONS
we can use built-in functions given in Python to perform various
advanced operations. For example, to calculate square root value of a number,
we need not develop any logic We can simply use the sqrt() function that is
already given in the 'math' module. For example, to calculate square root of
16, we can call the function as: sqrt(16). The function returns the positive
square root value of 16, i.e. 4.0.

For example, to import 'math' module, we can write:

import math

Once this is done, we can use any of the functions available in math module.
Now, can refer to sqrt() function from math module by writing module name
before the function as: math.sqrt().

x= math.sqrt (16)

Here, 'x' value will become 4.0.

We can also use import statement as:


import math as m

In this case, we are importing 'math' module and naming it as 'm' in our

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 12


INTRODUCTION TO PYTHON PROGRAMMING Unit II

program. Hence, hereafter, 'm' represents 'math'. So to calculate square root


of 16, we can write as:
x = m.sqrt (16)

import math statement is useful to import all the functions from math module.
On the other hand, if the programmer wants to import only one or two
functions from math module, he can write as:
from math import sqrt

Similarly, to import more than one function, one can write:


from math import factorial, sqrt

Here, the programmer is importing two functions by the names factorial() and
sqrt(). The programmer can use these functions without using module name
before them, as:
x = sqrt (16)
y = factorial (5)

Here, 'x' value will be 4.0 and y' value will be 120. The following table
summarizes important mathematical functions from math module. Please
note that these functions cannot be used with complex numbers. To use these
functions with complex numbers, a separate module by the name 'cmath' is
available in Python
Important Math functions

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 13


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 14


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Constants in Math Module

USING IDLE WINDOW


Click on 'Python IDLE window' icon available at task bar. This will open
the Python Shell window where we should type the program. When last
statement is typed and Enter is pressed, the result will be displayed, as shown
in Figure

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 15


INTRODUCTION TO PYTHON PROGRAMMING Unit II

USING COMMAND LINE WINDOW


Click on Python command line window' icon available at task bar. This will
open the Python command line window where we should type the program. When
last statement is typed and Enter is pressed, the result will be displayed, as shown
in Figure

EXECUTING SYSTEM PROMPT.


Open a text editor like Notepad or Edit Plus and then type the program.
Save the program as "circle.py" in a directory. Open command prompt window and
go to that directory where the program is stored. Then invoke python interpreter
by typing:

F:\PY>python area.py

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 16


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 17


INTRODUCTION TO PYTHON PROGRAMMING Unit II

CHAPTER-2
INPUT AND OUTPUT

The data given to the computer is called input. The results returned
by the computer are called output. So, we can say that a computer takes input,
processes that input and produces the output.

To provide input to a computer, Python provides some statements


which are called Input statements. Similarly, to display the output, there are
Output statements available in Python. We should use some logic to convert
the input into output.

OUTPUT STATEMENTS
To display output or results, Python provides the print() function.
This function used in different formats which are discussed here.

i)The print() Statement


When the print() function is called simply, it will throw the cursor to the
next line. It means that a blank line will be displayed.

ii)The print("string") Statement


A string represents a group of characters. When a string is passed to the
print() function, the string is displayed as it is.
Example: print("Hello")
Hello

We can use repetition operator (*) to repeat the strings in the output as:
Example: print (3* 'Hello').
HelloHelloHello

When we use '+' on strings, it will join one string with another string. Hence
'+' is called concatenation (joining) operator when used on strings.
Example: print("City name="+"Hyderabad")
City name=Hyderabad

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 18


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The '+'operator in the preceding statement joined the two strings without any
space in between. We can also write the preceding statement by separating
the strings using', '

Example: print("city name=","Hyderabad")


City name= Hyderabad

iii)The print(variables list) Statement


We can also display the values of variables using the print() function. A
list of variables can be supplied to the print() function as:

Example: a, b = 2, 4
print(a)
2

Example:print(a, b)
2 4
The values in the output are separated by a space by default. To
separate the output with a comma, we should use 'sep' attribute as shown
below. 'sep' represents separator. The format is sep="characters" which are
used to separate the values in the output.

Example: print(a, b, sep=",")


2,4

Example: print(a, b, sep=':')`


2:4

Example: print(a, b, sep='----')


2----4

When several print() functions are used to display output, each print()
function will display the output in a separate line as shown below:
Example: print("Hello")
print("Dear")
print('How are u?')
Output: Hello
Dear

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 19


INTRODUCTION TO PYTHON PROGRAMMING Unit II

How are U?

Each print() function throws the cursor into the next line after
displaying the output. We can ask the print() function not to throw the cursor
into the next line but display the output in the same line. This is done using
‘end' attribute. The way one can use it is end "characters" which indicates the
ending characters for the line.
Example: print(“Hello”, end=” “)
print(“Dear”, end=” “)"
print('How are u?', end=' ')
Output:HelloDearHow are u?

If we use end=’\t’ then the output will be displayed in the same line
but tab space will separate them as:
Example: print("Hello", end='\t')
print("Dear", end='\t')
print('How are u?', end='\t')
Output: Hello Dear How are U?

iv)The print(object) Statement


We can pass objects like lists, tuples or dictionaries to the print()
function to display the elements of those objects.
Example: lst = [10, 'A', 'Hello']
print (lst)
Output: [10, 'A', 'Hai']

Example: d='Idly': 30.00, ‘Roti':45.00, 'Chapati':55.50}


print (d)
Output: {'Idly': 30.0, 'Roti': 45.0, 'Chapati': 55.5}

v)The print("string", variables list) Statement


The most common use of the print() function is to use strings along
with variables inside the print() function.
Example: a=2
print(a, "is even number")
Output: 2 is even number

Example: print('you typed', a, 'as input')

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 20


INTRODUCTION TO PYTHON PROGRAMMING Unit II

You typed 2 as input

vi)The print(formatted string) Statement


The output displayed by the print() function can be formatted as we
like. The special operator ‘%’ (percent) can be used for this purpose. It joins a
string with a variable or value in the following format:
print("formatted string" % (variables list))

In the "formatted string", we can use %i or %d to represent decimal


integer numbers. We can use %f to represent float values. Similarly, we can
use %s to represent strings.
Example: x=10
print('value= %i' % x)
Output: value= 10

As seen above, to display a single variable (i.e. ‘x’) we need not wrap
it inside parentheses. When more than one variable is to be displayed, then
parentheses are needed as:
Example: x, y = 10, 15
print('x= %i y= %d' % (x, y))
Output: x= 10 y = 15

To display a string, we can use %s in the formatted string. When we


use %20s, it will allot 20 spaces and the string is displayed right aligned in
those spaces. To align the string towards left side in the spaces, we can use %-
20s.
Example: name='Linda'
print('Hello %s' % name)
Hello Linda

print(‘Hello (%20s) ‘% name)


Hello ( Linda)

print('Hello (%-20s)' % name)


Hello (Linda )

We can use %c to display a single character.


Example: name='Linda'
print('Hello %c, %c' % (name [0], name [1]))

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 21


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Output: Hello L, i

The above example displayed 0th and 1st characters from name variable.
We can use slicing operator on a string to display required characters from
the string.
For example, name[0:2] gives 0th to 1st characters from name as:
Example: print(‘Hello %s’ %(name [0:2]))
Output: Hello Li

To display floating point values, we can use %f in the formatted string.


If we use %8.2f, then the float value is displayed in 8 spaces and within these
spaces, a decimal point and next 2 fraction digits.

When we use %.3f, then the float value is displayed with 3 fraction
digits after the decimal point. However, the digits before decimal point will be
displayed as they are.
Example: num=123.456789
print(‘The value is: %f ’ % num)
The value is: 123.456789

print('The value is: %8.2f ' %num)


The value is: 123.46 # observe 2 spaces before the value

print('The value is: %.2f’ %num)


The value is: 123.46

INPUT STATEMENTS
To accept input from keyboard, Python provides the input() function. This
function takes a value from the keyboard and returns it as a string.
Example:str=input() # this will wait till we enter a string
Raj kumar # enter this string
print (str)
Raj kumar

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 the input() function as:
Example:str=input('Enter your name: ')
Enter your name: Raj kumar

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 22


INTRODUCTION TO PYTHON PROGRAMMING Unit II

print (str)
Raj kumar

Once the value comes into the variable 'str', it can be converted into 'int' or 'float' etc.
This is useful to accept numbers as:
Example:str = input('Enter a number: ')
Enter a number: 125
x = int(str) #str is converted into int
print(x)
125

We can use the int() function before the input() function to accept an integer from the
keyboard as:
Example:x = int(input('Enter a number: '))
Enter a number: 125
print (x)
125

Similarly, to accept a float value from the keyboard, we can use the float() function
along with the input() function as:
Example: x = float(input('Enter a number: '))
Enter a number: 12.345
print(x)
12.345
Program

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 23


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 24


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 25


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 26


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 27


INTRODUCTION TO PYTHON PROGRAMMING Unit II

COMMAND LINE ARGUMENTS

we can pass inputs to the program when we give run command. For example,
we write a program by the name 'add.py' that takes two numbers and adds them.
We can supply the two numbers as input to the program at the time of running the
program at command prompt as:

C:\>python add.py 10 22
Sum = 32

add.py is our Python program name. While running this program, we are passing two
arguments 10 and 22 to the program, which are called command line arguments.
These arguments are stored by default in the form of strings in a list with the name
'argv' which is available in sys module. Since argv is a list that contains all the values
passed to the program, argv[0] represents the name of the program, argv[1]
represents the first value, argv[2] represents the second value and so on.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 28


INTRODUCTION TO PYTHON PROGRAMMING Unit II

C:\> python add.py 10 22


If we want to find the number of command line arguments, we can use the len()
function as: len(argv). The following program reads the command line arguments
entered at command prompt and displays them.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 29


INTRODUCTION TO PYTHON PROGRAMMING Unit II

CHAPTER-3
CONTROL STATEMENTS

When we write a program, the statements in the program are normally executed one
by one. This type of execution is called 'sequential execution'.

Control Statements
Control statements are statements which control or change the flow of
Execution . The following are the control statements available in Python:
If statement
if….else statement
if…..elif….else Statement
While loop
for loop
else suite
break Statement
continue Statement
pass statement
assert statement
return statement

The if Statement
This statement is used to execute one or more statement depending on
whether a condition is True or not. The syntax or correct format of if statement is
given below:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 30


INTRODUCTION TO PYTHON PROGRAMMING Unit II

if condition:
statements

First, the condition is tested. If the condition is True, then the statements given after
colon (:) are executed. We can write one or more statements after colon (:). If the
condition is False, then the statements mentioned after colon are not executed.

We can also write a group of statements after colon. The group of statements in
Python is called a suite. While writing a group of statements, we should write them all
with proper indentation. Indentation represents the spaces left before the statements.
The default indentation used in Python is 4 spaces.

Observe that every print() function mentioned after colon is starting after 4 spaces
only, When we write the statements with same indentation, then those statements
are considered as a suite (or belonging to same group).

A Word on Indentation
Understanding indentation is very important in Python. Indentation refers to spaces
that are used in the beginning of a statement. The statements with same indentation

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 31


INTRODUCTION TO PYTHON PROGRAMMING Unit II

belong to same group called a suite.By default, Python uses 4 spaces but it can be
increased or decreased by the programmers.

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 syntax of if...
else statement is given below:

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 statements2. It is advised to use 4 spaces as indentation before
statements and statements2..

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
situation .Consider the following syntax of if ... elif ... else statement:
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 32


INTRODUCTION TO PYTHON PROGRAMMING Unit II

else:
statements4
When condition1 is True, the statements 1 will be executed. If condition 1 is
False, then condition2 is evaluated. When condition2 is True, the statements2 will be
executed. When condition2 is False, the condition3 is tested. If condition3 is True,
then statements3 will be executed. When condition3 is False, the statements4 will be
executed. It means statements4 will be executed only if none of the conditions
are True.

Observe colon (: ) after each condition. The statements1, statements2,


represent one statement or a suite. The final ‘else' part is not compulsory. It means,
it is possible to write if ... elif statement, without 'else' and statements4.

The while Loop


The while loop is useful to execute a group of statements several times
Repeatedly depending on whether a condition is True or False. The syntax or
format of while loop is

while condition:
statements

Here, ‘statements' represents one statement or a suite of 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 again
execute the statements. Then it will go back to check the condition once again. In this

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 33


INTRODUCTION TO PYTHON PROGRAMMING Unit II

way, as long as the condition is True, Python interpreter executes the statements
again and again. Only the condition is found to be False, then it will come out of the
while loop.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 34


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The for Loop


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 can work with sequence
like string, list, tuple, range etc. 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 the 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 Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must
use caution when using while loops because of the possibility that this condition
never resolves to a FALSE value. This results in a loop that never ends. Such a loop
is called an infinite loop.
An infinite loop might be useful in client/server programming where the server
needs to run continuously so that client programs can communicate with it as and
when required.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 35


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Here, ‘i’ value starts at 1. print(i) will display 1. Then the value of ‘i’ is incremented
by 1 so that it will become 2. In this way, 'i' values 1, 2, 3, up to 10 are displayed.
When 'i' value is 11, the condition, i.e. i<=10 becomes “False' and hence the loop
terminates.

In the previous while loop, what happens if we forget to write the last statement,
i.e. ‘i+=1' the initial ‘i’ value 1 is displayed first, but it is never incremented to reach
10. Hence this loop will always display 1 and never terminates. Such a loop is called
“infinite loop”. infinite loop is a loop that executes forever. To stop the program, we
have press Control+C at system prompt.

Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time
for each iteration of the "outer loop".
Example: adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

Example:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 36


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Output:

The else suite


In Python, it is possible to use ‘else’ statement along with for loop or while loops
form shown in Table:

The statements written after 'else' are called suite. The else suite will be always
executes irrespective of the statements in the loop are executed or not.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 37


INTRODUCTION TO PYTHON PROGRAMMING Unit II

It means, the for loop statement is executed and also the else suite is executed.
Suppose we write:

Here, the statement in the for loop is not even executed once, but the else suite
executed as usual. So, the point is this: the else suite is always executed.
But then when is this else suite useful?

Sometimes, we write programs where searching for an element is done in the


Sequence. When the element is not found, we can indicate that in the else suite easily.
In this else with for loop or while loop - is very convenient.

The break Statement


The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.
Example: for val in "string":
if val == "i":
break
print(val)

print("The end")

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 38


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Output:
s
t
r
The end

Example:

The continue Statement


Continue statement is a loop control statement that forces to execute the
next iteration of the loop while skipping the rest of the code inside the loop for the
current iteration only i.e. when the continue statement is executed in the loop,the
code inside the loop following the continue statement will be skipped for the
current iteration and the next iteration of the loop will begin.
Example: for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 39


INTRODUCTION TO PYTHON PROGRAMMING Unit II

g
The end

The pass Statement


The pass statement does not do anything. It is used with 'if' statement or inside a
loop to represent no operation. We use pass statement when we need a statement
syntactically but we do not want to do any operation.

The assert Statement


In Python, the assert statement is used to continue the execute if the given
condition evaluates to True. If the assert condition evaluates to
False, then it raises the AssertionError exception with the specified error message.
assert condition [, Error Message]
Example:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 40


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Example:

The return Statement

A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to the
caller.
Example:

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output:
15
25
45

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 41


INTRODUCTION TO PYTHON PROGRAMMING Unit II

CHAPTER-4
ARRAY IN PYTHON

ARRAY;

An array is an object that stores a group of elements (or values) of


same datatype. The main advantage of any array is to store and process a
group of elements easily.

There are two points we should remember in case of arrays in Python.



Arrays can store only one type of data. It means, we can store only
integer type elements or only float type elements into an array. But we
cannot store one integer,one float and one character type element into
the same array .

Arrays can increase or decrease their size dynamically. It means, we need
not declare the size of the array. When the elements are added, it will
increase its size and when the elements are removed, it will automatically
decrease its size in memory.

Advantages of Arrays
The following are some advantages of arrays:
 Arrays are similar to lists. The main difference is that arrays can store only
one type of elements; whereas, lists can store different types of elements.
When dealing with a huge number of elements, arrays use less memory than
lists and they offer faster execution than lists.
 The size of the array is not fixed in Python. Hence, we need not specify how
many elements we are going to store into an array in the beginning.
 Arrays can grow or shrink in memory dynamically (during runtime).
 Arrays are useful to handle a collection of elements like a group of numbers
or characters.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 42
INTRODUCTION TO PYTHON PROGRAMMING Unit II

 Methods that are useful to process the elements of any array are available in
'array'

Creating an Array:
Arrays hold data of same type. The type should be specified by using a type code at
the time of creating the array object as:
arrayname=array(type code, [elements])
The type code i, represents integer type array 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.

We will take an example to understand how to create an integer type array. We


should first write the module name ‘array' and then the type code we can use is ‘i’
for integer type array. After that the elements should be written inside the square
braces [| as,
a=array(‘I’,[4, 6, 2, 9])

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 43


INTRODUCTION TO PYTHON PROGRAMMING Unit II

This is creating an array whose name is ‘a' with integer type elements 4, 6, 2 and 9.
Similarly, to create a float type array, we can write:
arr=array(‘d’,[1.5, -2.2, 3, 5.75])
This will create an array by the name 'arr' with float type elements 1.5, -2.2, 3.0
and 5.75. The type code is d' which represents double type elements each taking 8
bytes memory.

Importing the Array Module;


There are three ways to import the array module into our program.
The first way is import the entire array module using import statement as,
import array
When we import the array module, we are able to get the array' class of that
module that helps us to create an array. See the following example:
a=array. array(‘i’, [4,6,2,9])
Here, the first 'array' represents the module name and the next 'array' represents
the class name for which the object is created. We should understand that we are
creating our array as an object of array class.

The second way of importing the array module is to give it an alias name, as:
import array as ar
Here, the array is imported with an alternate name ‘ar’. Hence we can refer to the
array class of 'ar' module as:
a=ar.array('i', [4,6,2,9])

The third way of importing the array module is to write:


from array import *

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 44


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The * symbol that represents 'all'. The meaning of this statement is this: import all
(classes, objects, variables etc) from the array module into our program. That
means we are specifically importing the 'array' class (because of * symbol) of
'array' module. So, there is no need to mention the module name before our array
name while creating it. We can create the array as:
a=array(‘i’, [4,6,2,9])
Here, the name 'array' represents the class name that is available from the 'array’
module.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 45


INTRODUCTION TO PYTHON PROGRAMMING Unit II

It is possible to create an array from another array. For example, there is an array
'arr’ as:
arrl = array('d', [1.5, 2.5, -3.5, 4])
This is a float type array with 4 elements. We want to create another array with the
name 'arr2’ from arrl. It means, 'arr2' should have same type code and same
elements as that of 'arr1’. For this purpose, we can write:
arr2 = array (arr1.typecode, (a for a in arr1))
Here, 'arr1.typecode' gives the type code character of the array 'arr1': This type
code is used for 'arr2' array also. Observe the expression:
a for a in arr1
The first 'a' represents that its value is stored as elements in the array 'arr2'. This
‘a’ value is got from 'a' (each element) in arr1. So, all the elements in arr1 will be
stored into arr2. Suppose, we write the expression,
arr2 = array (arr1.typecode, (a*3 for a in arr1))

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 46


INTRODUCTION TO PYTHON PROGRAMMING Unit II

In this case, the value of 'a' obtained from arr1, is multiplied by 3 and then stored
as element into arr2. So, arr2 will get the elements: 4.5, 7.5, -10.5, and 12.0.

Indexing and Slicing on Arrays;


An index represents the position number of an element in an array. For example,
when we create the following integer type array:
x=array('i', [10, 20, 30, 40, 50])
Python interpreter allocates 5 blocks of memory, each of 2 bytes size and stores
the elements 10, 20, 30, 40 and 50 in these blocks.
Figure shows the arrangement of elements the array 'x':

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 47


INTRODUCTION TO PYTHON PROGRAMMING Unit II

We can understand that the 0th element of the array is represented by xļ0|, the 1 st
element is represented by xļ1| and so on. Here, 0, 1. 2, etc. are representing the
position numbers of the elements. So, in general we can use i to represent the
position of any element. This i is called ‘index' of the array. Using index,
we can refer to any element of the array as x[i] where ‘i’ values will change from 0
to n-1.Here n represents the total number of elements in the array.

To find out the number of elements in an array we can use the len() function as:
n=len(x)
The len(x) function returns the number of elements in the array 'x' into n'.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 48


INTRODUCTION TO PYTHON PROGRAMMING Unit II

A slice represents a piece of the array. When we perform ‘slicing’ operations on


any array. we can retrieve a piece of the array that contains a group of elements.
Whereas indexing is useful to retrieve element by element from the array, slicing is
useful to retrieve a range of elements.
The general format of a slice is:
arrayname [start : stop:stride]
We can eliminate any one or any two in the items: 'start, 'stop' or 'stride' from the
above syntax. For example,
arr[1:4]
The above slice gives elements starting from 1st to 3rd from the array 'arr'.
Counting of the elements starts from 0. All the items 'start, 'stop' and 'stride'
represent integer numbers either positive or negative. The item 'stride' represents
step size excluding the starting element.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 49


INTRODUCTION TO PYTHON PROGRAMMING Unit II

From Program 7, we can understand that slicing can be used to create new arrays
from existing arrays.
For example, when we write:
y = X[-4:]
we are creating a new array y' with the last 4 elements of 'x' that we obtained
through slicing. Slicing can also be used to update an array. For example, to replace
the 1st and 2nd elements of ‘x’ array with the elements [5, 7] of another array, we
can write:
X[1:3] = array(‘i’, [5, 7])
The elements 5, 7 are stored in the positions 1 and 2 in the array ‘x’. The remaining
element of the array will not be changed.

Processing the Arrays;


The arrays class of arravs module in Python offers methods to process the arrays
easily. The programmers can easily perform certain operations by using these
methods. We should understand that a method is similar to a function that
performs a specific task. But methods are written inside a class whereas a function
can be written inside or outside the class, Methods are generally called as:
objectname.method().

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 50


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 51


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 52


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Types of Arrays:

When talking about arrays, any programming language like C or Java offers two
types of arrays. They are:

 Single dimensional arrays: These arrays represent only one row or one
column of elements. For example, marks obtained by a student in 5 subjects can
be written as 'marks' array, as:
marks = array ('i' , [50, 60, 70, 66, 72])
The above array contains only one row of elements. Hence it is called single
dimensional array or one dimensional array.
 Multi-dimensional arrays: These arrays represent more than one row and more
than one column of elements. For example, marks obtained by 3 students each
one in 5 subjects can be written as 'marks' array as:
marks = array([50, 60, 70, 66, 72],
[60, 62, 71, 56, 70],
[55, 59, 80, 68, 65])
The 1st student's marks are written in first row. The second student's marks are
in second row and the third student's marks are in third row. In each row, the
marks in 5 subjects are mentioned. Thus this array contains 3 rows and 5
columns and hence it is called multi-dimensional array.

In Python, we can create and work with single dimensional arrays only. Python
does not support multi-dimensional arrays. We construct multidimensional arrays
using third party packages like numpy(numerical python).

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 53


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Working with Arrays using numpy:

numpy is a package that contains several classes, functions, variables


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 transforms,

The arrays which are created using numpy are called n dimensional
arrays where n can be any integer. If n=1, it represents a one dimensional
array. If n=2, it is a two dimensional array. Similarly, if n=3, it is a three
dimensional array. The arrays created numpy can accept only one type of
elements. We cannot store different datatypes same array.

To work with numpy, we should first import numpy module into our
Python programs
import numpy
This will import numpy module into our progran so that we can use any of the
objects from that package. But, to refer to an object we should use the format:
numpy.object.

In above program we user array() function to create an array with 5


elements. Observe that we called this function as: numpy.array(). In this way,
adding the word ‘numpy’ before every object or function would be difficulty
for the programmer. Hence there is another way to write import statement as:

import numpy as np

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 54


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Here we are using ‘np’ to refer to the word ‘numpy’. Hence, wherever we need
to type ‘numpy’ , we simply type as ‘np’. This makes typing easy for the
programmer.

Cant we eliminate writing even np to refer to the objects or functions in our


program? Yes that is possible by writing import statement as:

from numpy import *

This will import everything (* means all) specifically from numpy package.
Now, we need not use any name to refer the objects or functions in our
program.

In above Program 16, we are straight away calling the function as array() and
there is no need of using any word before the function.

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() functions

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 55


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Creating Arrays using array():


We can call array() function of numpy module to create an array. When we create
an array, we can specify the datatype of the elements either as ‘int’ or ‘float’. We
can create an integer type array as:
arr = array([10, 20, 30, 40, 50], int)
We can also eliminate ‘int' in the above statement since Python can assess the
datatypes of elements.
To create an array with float type elements, we should specify ‘float' as:
arr = array([1.5, 2.5, 3, 4, -5.1], float)
The same statement can be rewritten by eliminating ‘float' as Python can judge the
datatypes of the elements. In the array, if Python interpreter finds one element
belonging to ‘float’ type, then it will convert all the other elements also into float
type by adding a decimal point after the element as:
arr = array ([10, 20, 30.1, 40])
If we display this array using print() function, we can see the array as:
[10. , 20. , 30.1, 40.]
To create an array with character type elements, we need not specify the datatype.
We can simply write:
arr = array (['a','b', 'c', 'd'])

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 56


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Creating Arrays using linspace:


The linspace() function is used to create an array with evenly spaced points
between a starting point and ending point. The form of the linspace() function is:
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. Let's take one example to understand this.
a = linspace (0, 10, 5)
In the above statement, we are creating an array 'a' with starting element 0 and
ending element 10. This range is divided into 5 equal parts and hence the points
will be 0, 2.5, 5,7.5 and 10. These elements are stored into 'a'. Please remember the
staring and elements O and 10 are included.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 57


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Creating Arrays using logspace;


The logspace() function is similar to linspace(). The linspace) function produces
the evenly spaced points. Similarly, logspace() produces evenly spaced points on a
logarithmically spaced scale. The logspace() function is used in the following
format:
logspace (start, stop, n)
The logspace() function starts at a value which is 10 to the power of 'start' and
ends at a value which is 10 to the power of stop'. If n' is not specified, then its value
is taken as 50.
For example, if we write:
a = logspace (1, 4, 5)
This function represents values starting from 101 to 104. These values are divided
into 5 equal points and those points are stored into the array 'a'. This can be seen
in sample

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 58


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Creating Arrays using arange() Function;


The arange() function in numpy is 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 one element prior to
'stop' in
steps of 'stepsize. If the 'stepsize' is omitted, then it is taken as 1. If the 'start' is
omitted,
then it is taken as 0. For example,
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 create an array with the elements starting from 1 to 9. So, the first element will
be 1. Since the stepsize is 3, we should 3 to get the subsequent elements. Thus, the
second element can be obtained as 1+3 = 4 and the third element can be obtained
as 4+3 = 7 and so on. Hence, the array will contain the following elements: 1 4 7|
arange (10, 1, -1)
Since the stepsize is -1, it represents the elements in descending order from 10 to
2, as:
[10 9 8 7 6 5 4 3 2].
The following example creates a float type array with stepsize 1.5:
arange (0, 10, 1.5)
In this case, the array elements will be: [0. 1.5 3. 4.5 6. 7.5 9. ]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 59


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Creating Arrays using zeros() and ones() Functions;


We can use the zeros() function to create an array with all zeros. The ones()
function is useful to create an array with all 1s. 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 is ‘float’
zeros (5)
This will create an array with 5 elements all are zeros, as: [0. 0. 0. 0. 0. ], If we
want this array in integer format, we can use ‘int' as datatype, as:
zeros (5 , int)
this will create an array as: 0 0 0 0 0 .
If we use ones() function, it will create an array with all elements 1. For example.
ones(5, float)
will create an array with 5 integer elements all are 1s as: [1. 1. 1. 1. 1. ].

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 60


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Mathematical Operations on Arrays;


It is possible to perform various mathematical operations like addition,
subtraction, division, etc. on the elements of an array. Also, the functions of ‘math'
module can be applied to the elements of the array. For example, to add the value 5
to every element of an array, we can write:
arr = array ([10, 20, 30.5, -40)
arr = arr+5
This will store the following elements into the array: (15. 25. 35.5 -35.]. In the
same way, we can perform addition, subtraction, multiplication, division etc.
operations on two different arrays as:
arr1 = array([10, 20, 30.5, -40])
arr2 = array([1, 2, 3, 4])
arr3 = arr1 – arr2
The resultant array 'arr3’ contains the following elements: [9. 18. 27.5 -44. ]. So, to
add two arrays n add two arrays ‘a’ and 'b’, we can simply write a + b. Similarly, to
divide one array 'a' with another array 'b’, we can write a/b. These kinds of
operations are called vectorized operations since the entire array (or vector) is
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 61
INTRODUCTION TO PYTHON PROGRAMMING Unit II

processed just like a variable. Vectorized operations are important because of two
reasons:
 Vectorized operations are faster. Adding two arrays in the form of a+b is
much faster than taking the corresponding elements of both the arrays and
then adding them.
 Vectorized operations are syntactically clearer. To add two arrays, we can
simply write a+b. This is clearer than using loops and iterating through all
the elements of the arrays while adding them.
 Vectorized operations provide compact code.
We can apply mathematical functions like sin(), cos(), sqrt(), exp(), abs(), etc. on
the elements of the array. All these functions are re-defined in numpy module.
Table we can see the list of functions that can be used on numpy arrays:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 62


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 63


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Comparing Arrays;
We can use the relational operators >, >=, <, <=, == and = to compare the arrays of
same size. These operators compare the corresponding elements of the arrays and
return another array with Boolean type values. It means the resultant array
contains elements which are True or False.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 64


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The any() function can be used to determine if any one element of the array
is True. The all() function can be used to determine whether all the elements
in the array are True.
The any() and all0 functions return either True or False.

The functions logical_and(), logical_or() and logical_not() are useful to get the
Boolean array as a result of comparing the compound condition. Compound
condition is a combination of more than one simple condition.

For example: c= logical_and (a>0, a<4)

In the above statement, the logical _and() function applies the compound
condition a>0 and a<4 on every element of the array 'a' and returns another
array 'c' that contains True or False values. We should understand that Python
represents 0 as False and any other number as True.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 65


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The where() function can be used to create a new array based on whether a
given condition is True or False. The syntax of the where() function is:

array = where(condition, expression1, expression2)

If the ‘condition’ is true, ‘expression 1' is executed and the result is stored into
the array, else ‘expression 2’ is executed and its result is stored into the array.

For example,
a= array ([10, 21, 30, 41, 50], int)

The new array ‘c’ contains elements from 'a' based on the condition a%2==0.
This condition is applied to each element of the array 'a' and if it is True, the
element of 'a' is stored into 'c' else '0' is stored into c. Hence the array 'c' looks
like this: [10 0 30 0 50]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 66


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The nonzero() function is useful to know the positions of elements which are
non zero.
This function returns an array that contains the indexes of the elements of the
array which are not equal to zero. For example,
a = array ([1, 2, 0, -1, 0, 6], int)

In the preceding array, the elements which are non zero are: 1, 2, -1 and 6.
Their positions or indexes are: 0, 1, 3, 5. These indexes can be retrieved into
another array 'c' as:
C= nonzero (a)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 67


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Aliasing the Arrays;


If 'a' is an array, we can assign it to b', as:
b= a
This is a simple assignment that does not make any new copy of the array 'a'. It
means ‘b' is not a new array and memory is not allocated to b'. Also, elements from
'a' are not copied into ‘b’ since there is no memory for ‘b’. Then how to understand
this assignment statement? We should understand that we are giving a new name
‘b' to the same am referred by 'a'. It means the names 'a' and b' are referencing
same array. This is called 'aliasing'.

Figure shows the aliasing of array a as b:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 68


INTRODUCTION TO PYTHON PROGRAMMING Unit II

'Aliasing' is not 'copying'. Aliasing means giving another name to the existing
object. Hence, any modifications to the alias object will reflect in the existing object
and vice versa.

Viewing and Copying Arrays;


We can create another array that is same as an existing array. This is done by the
view()method. This method creates a copy of an existing array such that the new
array will also contain the same elements found in the existing array. The original
array and the newly created arrays will share different memory locations. If the
newly created array is modified, the original array will also be modified since the
elements in both the arrays will be like mirror images.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 69


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 70


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Viewing is nothing but copying only. It is called 'shallow copying' as the


elements in the view when modified will also modify the elements in the
original array. So. Both the arrays will act as one and the same. Suppose we
want both the arrays to be independent and modifying one array should not
affect another array, we should go for ‘deep copying’.This is done with the
help of copy0 method. This method makes a complete copy of an existing
array and its elements. When the newly created array is modified, it will not
be any connection between the elements of the two arrays. Figure shows
copying an array as another array:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 71


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Slicing and Indexing in numpy Arrays;


Slicing refers to extracting a range of elements from the array. The format of slicing
operation is:
arrayname [start : stop:stepsize]
The default value for 'start’ is 0, for 'stop' is n (n is number of elerments) and for
'stepsize'
is 1. Counting starts from 0th position. For example, if we write:
a = [10, 11, 12, 13, 14, 15]
a[1:6:2]
Here ‘start' is 1. So, it will extract from 1st element, i.e. from 11. Since 'stop' is 6, it
will stop at one element prior to 6. That means it will stop at 15. Since 'stepsize' is
2, we should add 2 to the starting index to get the next element index, as: 1+2 = 3rd
element and then 3+2= 5th element. So, the following elements will be extracted:
[11, 13, 15].

Suppose, we write a[:] or a[::] without specifying anything for start, stop and
stepsize, it
will extract from 0th element till the end of the array. So, all elements are

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 72


INTRODUCTION TO PYTHON PROGRAMMING Unit II

extracted. Suppose, we write a[2:], it starts at 2nd element and ends at last
element. So, the extracted array will be:
[12, 13, 14, 15]
When negative number ‘i’ is used for 'start', it should be taken as n+i. When
negative number ‘j' is used for 'stop', it should be taken as n+j. When negative
number is used for ‘stepsize’, the stepping goes towards smaller indexes. Thus, if
we write:
a[-1:-4:-1]
Since there are totally 6 elements in the array 'a'. we have 'start' as 6-1 = 5, 'stop’
is 6-4=2, and 'stepsize' is -1, i.e. going towards least index. Hence, it will retrieve
elements starting from 5th element till one element prior to 2nd element going
backwards. So, the retrieved array will be: [15, 14, 13].

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 73


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Dimensions of Arrays;
Dimension of an array represents the arrangement of elements in the
array. If the elements are arranged horizontally, it is called a row and if the
elements are arranged vertically, then it is called a column.
When an array contains only 1row or only 1 column of elements, it is
called Single dimensional array or one dimensional array (1 D array). In
following example, 'arr1' represents a lD array that contains 1 row and 'arr2’

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 74


INTRODUCTION TO PYTHON PROGRAMMING Unit II

represents another 1D array that contains only 1 column.

If an array contains more than 1 row and 1 column, then it is called two
dimensional array or 2D array. In the following example, we are creating 'arr2' as a
2D array with 2 rows and 3 columns.

We can imagine a 2D array as a combination of several 1D arrays. In the


above example, each row of 'arr2' in turn represents a lD array. Similarly, we can
imagine a 3D array as a combination of several 2D arrays. The following example
creates a 3D array by the name 'arr3' that contains two 2D arrays. Each of these 2D

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 75


INTRODUCTION TO PYTHON PROGRAMMING Unit II

arrays contains 2 rows and 3 columns of elements.

If we display the elements of this 3D array using print(arr3), it shows the following
output:

The 2D arrays and 3D arrays are called multi-dimensional arrays in general.

Attributes of an Array;
Numpy's array class is called ndarray. It is also known by alias name array.
Remember that there is another class 'array' in Python that is different from
numpy’s array class. This class contains the following important attributes (or
variables):

i)The ndim Attribute


The ndim' attribute represents the number of dimensions or axes of the array. The
number of dimensions is also referred to as ‘rank'. For a single dimensional arrav,
it is 1 and for a two dimensional array, it is 2. Consider the following code snippet:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 76


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Now, consider the following lines of code:

ii)The shape Attribute


The 'shape' attribute gives the shape of an array. The shape is a tuple listing the
number of elements along each dimension. A dimension is called an axis. For a 1D
array, shape gives the number of elements in the row. For a 2D array, it specifies
the number of rows and columns in each row. We can also change the shape using
'shape' attribute.
Consider the following code snippet:

Now, consider the following lines of code:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 77


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Also, consider the following lines of code:

iii)The size Attribute


The size' attribute gives the total number of elements in the array. For example,
consider the following code snippet:

Now, consider the following lines of code:

iv)The itemsize Attribute


The itemsize' attribute gives the memory size of the array element in bytes. As we
know, 1 byte is equal to 8 bits. For example consider the following code snippet:

Now, consider the following lines of code:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 78


INTRODUCTION TO PYTHON PROGRAMMING Unit II

v)The dtype Attribute


The ‘dtype' attribute gives the datatype of the elements in the array. For example,
consider the following code snippet:

Now, consider the following lines of code:

vi)The nbytes Attribute


The ‘nbytes' attribute gives the total number of bytes occupied by an array. The
total number of bytes = size of the array * item size of each element in the array.

The reshape() Method


The ‘reshape()' method is useful to change the shape of an array. The new array

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 79


INTRODUCTION TO PYTHON PROGRAMMING Unit II

should have the same number of elements as in the original array. For example,

Now, consider the following code snippet:

Also, consider the following code snippet:

The flatten() Method;


The flatten() method is useful to return a copy of the array collapsed into one
dimnension.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 80


INTRODUCTION TO PYTHON PROGRAMMING Unit II

For example, let's take a 2D array as:

By using the flatten() method, we can convert this array into 1D array as:

Working with Multi-dimensional Arrays;


The 2D arrays, 3D arrays etc. are called multi-dimensional arrays. A 2D array
contains more than 1 row and 1 column and it can be treated as a combination of
several 1D arravs. A 2D array is also considered as a matric.

For example, a 2D array with ‘m' rows and ‘n' columns is called m x n matrix.
As we know in Mathematics, a matrix contains elements arranged in several rows
and columns. Hence, we can take a matrix as a 2D array and vice versa.

We can create multi-dimensional arrays in the following ways:

 Using array() function


 Using ones() and zeroes() functions
 Using eye() function
 Using reshape() function

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 81


INTRODUCTION TO PYTHON PROGRAMMING Unit II

 The array() Function


Numpy's array() function can be used to create a multidimensional array. Usually,
we pass lists of elements to this function. If we pass one list of elements to this
function, then it will create a 1D array. If we pass two lists of elements, then this
function creates a 2D array.

Even though the elements are displayed in 2 rows and 4 columns, the internal
memory allocated to all these elements would be in the form of a single row
containing 8 blocks (2 X 4 = 8). The elements are stored in the contiguous
memory locations as shown below:

 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), dtype)
Here, ‘r' represents the number of rows and 'c' represents the number of
columns, ‘dtype’ represents the datatype of the elements in the array. For ex

a = ones ((3, 4), float)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 82


INTRODUCTION TO PYTHON PROGRAMMING Unit II

will create a 2D array with 3 rows and 4 columns and the datatype is taken as
float. If ‘dtype' is omitted, then the default datatype taken will be ‘float'. Now, if
we display 'a', we can see the array as:

The decimal point after each element represents that the elements are float type.
Just like the ones() function, we can also use the zeros() function to create a 2D
array with elements filled with zeros. Suppose, we write:
b=zeros((3,4), int)
Then a 2D array with 2 rows and 4 columns will be created where all elements
will be Os, as shown below:

The eye() Function


The eye() function creates a 2D array and fills the elements in the diagonal
with 1s. 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 is
‘float’. For example, eye(3) will create a 3x3 array and fills the diagonal
elements with ls as shown below:

The reshape() Function


The reshape() function has been already discussed in the previous section. We
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 83
INTRODUCTION TO PYTHON PROGRAMMING Unit II

will have elaborate discussion about this function now. This function is useful
to convert a lD array into a multidimensional (2D or 3D) array. The syntax of
writing this function is:

reshape (arrayname, (n, r, c))

Here, 'arrayname' represents the name of the array whose elements to be


converted. ‘n' indicates the number of arrays in the resultant array. ‘r’, ‘c’
indicates the number of rows and columns, respectively. For example, we take
a 1D array 'a' with 6 elements as:

a = array ([1, 2, 3, 4, 5, 6])

To convert 'a' into a 2D array using the reshape() function, we can write:
b= reshape (a, (2, 3))

We are converting the elements of the array 'a' into a 2D array with 2 rows
and 3 columns, and the resultant array is ‘b', So, the 2D array b' looks like this:

Observe the starting two pairs of square brackets which indicate that it is a 2D
array. Suppose, we write:
b= reshape (a, (3, 2))
This will convert 'a' into a 2D array with 3 rows and 2 columns that looks like
this:

It is possible to use the reshape() function to convert a 1D array into a 3D


array. Let's take a 1D array 'a' with 12 elements as:
a = arange(12)
Here, we are creating the array a' with 12 elements starting from 0 to 11 as:
[0 1 2 3 4 5 6 7 8 9 10 11]
Now, to convert this 1D array into a 3D array, we can use the reshape() function ae
b=reshape (a, (2, 3, 2))

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 84


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Here, ‘a' represents the arrayname that is being converted. In the reshape()
function 'a', observe the figures (2, 3, 2). They represent that we want 2 arrays
each with 3 rows and 2 columns. So, the resultant 3D array ’b'looks like this:

So, ‘b' is a 3D array of size 2x3x2. Suppose, we write:


b= reshape (a, (3, 2, 2))
Then we can expect a 3D array with 3 inner arrays each one having 2 rows and 2
columns of elements. It means the size of 'b' will be 3x2x2 and can be displayed as:

Indexing in Multi-dimensional Arrays;

Index represents the location number. The individual elements of a 2D array


can be accessed by specifying the location number of the row and column of
the element in the array as:

Let's see how to retrieve elements from a 2D array. Suppose 'a' is the array
name. len(a) function will give the number of rows in the array. a[0]
represents the 0th row, a[1] represents the 1st row, etc. So, in general, aļi]
represents the ith row elements. Hence, to display only rows of the 2D array,
we can write:
for i in range(len(a)):
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 85
INTRODUCTION TO PYTHON PROGRAMMING Unit II

print (a [i])
Each row may contain some columns which represent the elements. To know,
how many elements are there in a row, we can use len(a[i]). Here, if i = 0, then
len(a[0]) represent the number of columns in 0th row. Similarly if i=1, then
len(a|1]) represents the number of columns in 1 row and so on. In this way,
len(a[i]) represents the number of column in ith row. So, the following loops
will access all elements from the 2D array:
for i in range(len (a)) :
for j in rangelen(ali
print (a[i][j], end=’ ‘)
In the preceding code, the outer for loop represents the rows and the inner for loop
represents the columns in each row. The individual elements can be retrieved as
a[i][j]. Figure shows how to access the elements of a 2D array with 3 rows and 3
cols:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 86


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Slicing the Multi-dimensional Arrays;


A slice represents a part or piece of the array. In the previous sections, we already
discussed about slicing in case of single dimensional arrays. Now, we will see how
to do slicing in case of multi-dimensional arrays, especially in 2D arrays. We take a
2D array with 3 rows and 3 columns as:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
We can reshape this array such that it will show elements in 3 rows and 3 columns,
as:
a = reshape (a, (3,3))
Now, print(a) will display the 2D array as:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 87


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The default value for 'start' is 0, for 'stop' is n (n is number of elements) and for
'stepsize’ is 1. Counting starts from 0th position. So, if we do not mention these
values, then starting from 0th element till the last element, the entire array will be
displayed. For example, if we write:
a[: , :]
a[ : ]
a[: :]
Any of the above will display the entire 2D array as:

Suppose, we want to display the 0th row from the array, we can write:
a[0, :]
Observe the O in the place of the row'. It will refer to 0th row. In the place of
'column', we used ‘:’ that refers to all columns (or elements) in that row. As a result
it will display |1 2 3]. Similarly, a[1,:]refers to 1st row and a[2, :] refers to 2nd row.
Suppose, we want to display Oth column of the array, we can write:
a[:, 0]
This will refer to the 0th column, i.e. [1 4 7]. Similarly, a|:, 1| refers to 1st column and
a[:,2] refers to 2nd column.

If we want to retrieve only a particular element, then we have to provide both the

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 88


INTRODUCTION TO PYTHON PROGRAMMING Unit II

row and column positions. For example, to retrieve 0th row and 0th column element,
we can write:
a[0:1, 0:1]
This will refer to the element 1 in the array. Similarly, to access the 1st row and 2nd
column element, we can write:
a[1:2, 1:2]
This will refer to the element 5. Similarly, to access the 2nd row and 2nd column
element, we can write:
a[2:3, 1:2]
This will refer to 8.

For the same of better understanding, let's create a 2D array with 5 rows and 5
columns with elements from 11 to 35. This can be done as:
a = reshape (arange (11, 36, 1), (5,5))
print (a)
The preceding lines of code will display the following output:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 89


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Suppose, we want to display the left top 2 rows and 3 columns, we can write as:
print (a [0:2, 0:3])
The preceding lines of code will display the following output:

This can be understood better from below diagram

In the same way, we can access the right top 2 rows and 3 columns as:
print(a[0:2, 2:])
The preceding line of code will display the following output:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 90


INTRODUCTION TO PYTHON PROGRAMMING Unit II

To access the lower right 3 rows and 2 columns, we can write:


print(a[2: ,3:])
The preceding line of code will display the following output:

MATRICES IN NUMPY;
In Mathematics, a matrix represents a rectangular array of elements
arranged in rows and columns. It means elements are available in a matrix in the
form of several rows and columns. If a matrix has only 1 row, it is called a 'row
matrix'. If a matrix has only column, then it is called as 'columnn matrix'. We can
understand that the row matrix and column matrices are nothing but 1D arrays.
When a matrix has more than 1 row and more than 1 column, it is called m
x n matrix where m represents the rows and n represents the columns. Thus, a 2 x
3 matrix contains 2 rows and 3 columns. We can show these matrices using numpy
2D arrays. To work with matrices, numpy provides a special object called matrix.
In numpy, a matrix is a specialized 2D array that retains its 2D nature through
operations.
We can create numpy matrices using the following syntax:
matrix-name = matrix(2D array or string)
It means, the matrix object receives a 2D array or a string that contains elements
which can be converted into a matrix. For example, we are taking a 2D array with 2

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 91


INTRODUCTION TO PYTHON PROGRAMMING Unit II

rows and 3 columns as:


arr = [[1, 2, 3], (4, 5, 6]]
This array can be converted into a matrix a' as:
a =matrix (arr)
If we display the matrix 'a', we can see the following format:

Alternately, we can also pass the 2D array directly to matrix object as:
a = matrix([[l, 2,3], [4,5,6]])
Another way of creating a matrix 1s by passing a string with elements to matrix
object as:

We can also pass the string directly to matrix object as:


b = matrix("1 2; 3 4; 5 6")
which will also create the matrix ‘b’ as indicated above.

GETTING DIAGONAL ELEMENTS OF A MATRIX;


To retrieve the diagonal elements of a matrix, we can use diagonal() function as:
a = diagonal (matrix)
The diagonal() function returns a 1D array that contains diagonal elements of the
original matrix. To understand this function, we can take an example.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 92


INTRODUCTION TO PYTHON PROGRAMMING Unit II

a = matrix('1 2 3; 4 5 6; 7 8 9’)
print (a)
The preceding lines of code will display the following output:
([1 2 3]
[4 5 6]
[7 8 9]]

Consider the following code:


d= diagonal (a)
print (d)
The preceding lines of code will display the following output:
[1 5 9 ]

FINDING MAXIMUM AND MINIMUM ELEMENTS;


To know the maximum element, we can use max() method and to know the
minimum element, we can use min() methods. These methods should be called
using the matrix name. See the following examples:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 93


INTRODUCTION TO PYTHON PROGRAMMING Unit II

FINDING SUM AND AVERAGE OF ELEMENTS;


To find sum of all the 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. See the following examples:

PRODUCTS OF ELEMENTS;

It is possible to know the products of elements in a matrix. For this


purpose, numpy provides prod() method. For example, prod(0) returns a
matrix that contains the product of elements in each column of the original
matrix. prod(1) returns a matrix that contains products of elements in each
row. These methods should be called using the matrix name.

As an example, we are creating a matrix from a 3 x 4 array as:

m = matrix(arange (12) .reshape (3,4))

This will create a matrix m' with elements from 0 to 11 in the form of 3 rows
and 4 columns as:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 94


INTRODUCTION TO PYTHON PROGRAMMING Unit II

To find the products of elements column-wise, we can call prod() method as:
a = m.prod (0)

The array ‘a’ looks like this: [[ 0 45 120 231]]. Each of these values
represents products of elements present in 0th column, 1st element, and so on
up to 3rd column. Now, to find the products of elements row-wise, we can call
prod() method as:
b=m.prod (1)

SORTING THE MATRIX;

numpy provides sort() function that sorts the matrix elements into ascending
order. See the syntax of this function:

sort (matrixname, axis)

If we use, axis=1, it sorts the elements in each row into ascending order. If we
use, axis=0, then it sorts the elements in each column into ascending order.
The default value of axis is 1. It means, if we do not mention 'axis', then its
value will be taken as 1. In the following example, we are taking a matrix 'm'
with 2 rows and 3 columns as:

m= matrix([[5, 4, 1], [2, 7, 0]])


print (m)

The preceding lines of code will display the following output:


[[ 5 4 1]
[ 2 7 0]]

To sort the elements in the rows, we can use sort() function as:
a = sort (m)
print(a)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 95


INTRODUCTION TO PYTHON PROGRAMMING Unit II

The preceding lines of code will display the following output:


[[ 1 4 5]
[ 0 2 7]]

Observe the sorted matrix 'a' contains the elements in each row arranged in
ascending order. To sort the elements vertically, i.e. column-wise, we can use
sort() function with axis=0 attribute as:

b = sort (m, axis=0)


print (b)

The preceding lines of code will display the following output:


[[ 2 4 0]
[ 5 7 1]]

TRANSPOSE OF A MATRIX;

Rewriting matrix rows into columns and vice versa is called ‘transpose'.
Thus, the rows in the original matrix will become columns in the transpose
matrix and the columns in the original matrix will become rows in the
transpose matrix. It means if the original has m x n size, the transpose matrix
will have n x m size. To find the transpose, we can use transpose() and get()
methods in numpy. These methods should be called using matrix name.
Consider the following code snippet:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 96


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 97


INTRODUCTION TO PYTHON PROGRAMMING Unit II

Matrix Addition and Multiplication


We can use arithmetic operators like +,- and / to perform addition, subtraction and
division operations on 2 matrices. Consider the following code snippet:

We can use * operator to perform matrix multiplication. Please remember this


operator does not multiply the corresponding elements of the matrices to produce
the new matrix.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 98


INTRODUCTION TO PYTHON PROGRAMMING Unit II

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 99

You might also like