0% found this document useful (0 votes)
8 views

PYTHON NOTES 1,2,3

This document serves as an introduction to Python programming, covering fundamental concepts such as program structure, indentation, comments, variables, and data types. It explains various operators, including arithmetic, relational, logical, bitwise, assignment, identity, and membership operators, along with input/output basics and data structures like lists, tuples, sets, and dictionaries. The document provides examples and outputs for better understanding of these concepts.

Uploaded by

amalamargret.cse
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)
8 views

PYTHON NOTES 1,2,3

This document serves as an introduction to Python programming, covering fundamental concepts such as program structure, indentation, comments, variables, and data types. It explains various operators, including arithmetic, relational, logical, bitwise, assignment, identity, and membership operators, along with input/output basics and data structures like lists, tuples, sets, and dictionaries. The document provides examples and outputs for better understanding of these concepts.

Uploaded by

amalamargret.cse
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/ 90

UNIT I INTRODUCTION TO PYTHON

Structure of Python Program – Underlying mechanism of Module Execution –


Branching and Looping – Problem Solving Using Branches and Loops – Functions –
Lambda Functions – Lists and Mutability – Problem Solving Using Lists and
Functions.

INTRODUCTION TO PYTHON

The structure of a Python program:

A program consists of a set of statements. Each statement can contain one or more
mathematical expressions, and each expression consists of literals, identifiers and operators.
Python runs a program by executing its statements, each of which fulfills a specific
functionality.
Python Indentation:

Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in
Python.

Eg:
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to python programming...')
else:
print('retype the URL.')
print('All set !')

output:
Logging on to python programming...
All set !
Python Comments:

Comments are useful information that the developers provide to make the reader understand
the source code. It explains the logic or a part of it used in the code. There are two types of
comment in Python:

Single line comments: Python single line comment starts with hashtag symbol with no
white spaces.

Eg:
# This is a comment
# Print “python programming !”

Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a


delimiter (“””) on each end of the comment.

Eg:
print("Python Programming")

Variables:

Variables in Python are not “statically typed”. We do not need to declare variables before
using them or declare their type. A variable is created the moment we first assign a value to
it.

Eg:

# An integer assignment
age = 18

# A floating point
salary = 1456.8

# A string
name = "Sam"

print(age)
print(salary)
print(name)

Output:

18
1456.8
Sam

Python Operators:
Operators are the main building block of any programming language. Operators allow the
programmer to perform different kinds of operations on operands. These operators can be
categorized based upon their different functionality:

Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division.

# Examples of Arithmetic Operator


a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

# Print Results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)

Output:
13
5
36
2.25
2
1

Relational Operators:
Relational operators compares the values. It either returns True or False according to the
condition.

# Examples of Relational Operators


a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)

Output:
False
True
False
True
False
True

Logical Operators: Logical operators perform Logical AND, Logical OR and Logical NOT
operations.
# Examples of Logical Operator
a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
# Print not a is False
print(not a)
Output:
False
True
False

Bitwise operators:
Bitwise operator acts on bits and performs bit by bit operation.

# Examples of Bitwise operators


a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)

Output:
0
14
-11
14
2
40

Assignment operators: Assignment operators are used to assign values to the variables.
# Examples of Assignment operators

Special operators: Special operators are of two types-

 Identity operator that contains is and is not.


 Membership operator that contains in and not in.

# Examples of Identity and


# Membership operator
a1 = 'Python Programming'
b1 = 'Python Programming'

# Identity operator
print(a1 is not b1)
print(a1 is b1)

# Membership operator
print("P" in a1)
print("G" not in b1)

Output:

False
True
True
True
Basics of Input/Output:
Taking input from user –

Python provides us with two inbuilt functions to read the input from the keyboard.

Raw_input(): This function works in older version (like Python 2.x). This function takes
exactly what is typed from the keyboard, convert it to string and then return it to the variable
in which we want to store.
For example:
# Python program showing
# a use of raw_input()
g = raw_input("Enter your name : ")
print g

input(): This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether the user entered a string or a number or
list.
For example:
# Python program showing
# a use of input()
val = input("Enter your value: ")
print(val)

Printing output to console –


using the print() function where you can pass zero or more expressions separated by commas.
# how to print data on a screen
# One object is passed
print("Computer Programming")
x=5
# Two objects are passed
print("x =", x)
# code for disabling the softspace feature
print('C', 'P', 'II', sep ='')
# using end argument
print("Python", end = '@')
print("Programming")

Output:
Computer Programming
x=5
CPII
Python@Programming
Python Data Types:

Data Types are the classification or categorization of data items.

Numeric:

In Python, numeric data type represents the data which has numeric value.
 Integer
 Float
 Complex Number

Example Program:
# Python program to demonstrate numeric value
print("Type of a: ", type(5))
print("\nType of b: ", type(5.0))
c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

Sequence Type:

In Python, a sequence is the ordered collection of similar or different data types. Sequences
allow storing multiple values in an organized and efficient fashion. There are several
sequence types in Python –

1. String
2. List
3. Tuple

1) String:
A string is a collection of one or more characters put in a single quote, double-quote or
triple quote.
In python there is no character data type, a character is a string of length one. It is
represented by str class.
Strings in Python can be created using single quotes or double quotes or even triple
quotes.

Example Programs:

# Python Program for Creation of String

# String with single quotes


print('Welcome to Computer Programming')

# String with double quotes


print("I'm a Programmer")

# String with triple quotes


print('''I'm a Programmer and I love to do programming in "Python"''')
Output:

Welcome to Computer Programming


I'm a Programmer
I'm a Programmer and I love to do programming in "Python"

# Python Program to Access characters of String

String1 = "Python Programming"


# Printing First character
print(String1[0])
# Printing Last character
print(String1[-1])

Output:
P
g

2) List:
 Lists are just like the arrays, declared in other languages.
 A single list may contain Datatypes like Integers, Strings, as well as Objects.
 The elements in a list are indexed according to a definite sequence and the indexing of
a list is done with 0 being the first index.
It is represented by list class.
Example Program:

# Python program to demonstrate Creation of List


# Creating a List
List = [ ]
print(List)
# Creating a list of strings
List = ['Computer Programming', 'Python']
print(List)
# Creating a Multi-Dimensional List
List = [['Computer', 'Programming'], ['Python']]
print(List)
Output:

[]
['Computer Programming', 'Python']
[['Computer', 'Programming'], ['Python']]

Adding Elements to a List: Using append(), insert() and extend():

# Python program to demonstrate Addition of elements in a List

# Creating a List
List = [ ]
# Using append()
List.append(1)
List.append(2)
print(List)
# Using insert()
List.insert(3, 12)
List.insert(0, 'Python')
print(List)
# Using extend()
List.extend([8, 'Python', 'Programming'])
print(List)

Output:
[1, 2]
['Python', 1, 2, 12]
['Python', 1, 2, 12, 8, 'Python', 'Programming']

Accessing elements from the List :


Use the index operator [ ] to access an item in a list.
In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-
3].
Example Program:

# Python program to demonstrate accessing of element from list


List = [1, 2, 3, 4, 5, 6]
# accessing a element
print(List[0])
print(List[2])
# Negative indexing
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output:
1
3
6
4

Removing Elements from the List: Using remove() and pop():

# Python program to demonstrate Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
# using Remove() method
List.remove(5)
List.remove(6)
print(List)
# using pop()
List.pop()
print(List)

Output:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4, 7, 8, 9, 10, 11]

3) Tuple:

 Tuple is an ordered collection of Python objects much like a list.


 The important difference between a list and a tuple is that tuples are immutable.
 It is represented by tuple class.
 In Python, tuples are created by placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping of the data sequence.

Example Programs:

# Python program to demonstrate creation of Set


# Creating an empty tuple
Tuple1 = ( )
print (Tuple1)
# Creating a tuple of strings
print(('Computer', 'Program'))
# Creating a Tuple of list
print(tuple([1, 2, 4, 5, 6]))
# Creating a nested Tuple
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Python', 'Programming')
Tuple3 = (Tuple1, Tuple2)
print(Tuple3)

Output:
()
('Computer', 'Program')
(1, 2, 4, 5, 6)
((0, 1, 2, 3), ('Python', 'Programming'))

Accessing element of a tuple :


Use the index operator [ ] to access an item in a tuple.

# Python program to demonstrate accessing tuple


tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print(tuple1[0])
# Accessing element using Negative
# Indexing
print(tuple1[-1])

Output:
1
5

Deleting/updating elements of tuple:

Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be
reassigned to the same name.

# Python program to demonstrate updation / deletion from a tuple


tuple1 = tuple([1, 2, 3, 4, 5])
# Updating an element
tuple1[0] = -1
# Deleting an element
del tuple1[2]

Output:
Traceback (most recent call last):
File "/home/084519a8889e9b0103b874bbbb93e1fb.py", line 11, in
tuple1[0] = -1
TypeError: 'tuple' object does not support item assignment

Traceback (most recent call last):


File "/home/ffb3f8be85dd393bde5d0483ff191343.py", line 12, in
del tuple1[2]
TypeError: 'tuple' object doesn't support item deletion

Boolean
Booleans are data type with one of the two built-in values, True or False. It is denoted by the
class bool.

# Python program to demonstrate boolean type


print(type(True))
print(1>2)
print('a'=='a')
Output:
<class 'bool'>
False
True

Set

 In Python, Set is an unordered collection of data type that is iterable, mutable and has
no duplicate elements.
 The order of elements in a set is undefined though it may consist of various elements.
 Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces {}, separated by ‘comma’.

# Python program to demonstrate Creation of Set in Python


# Creating a Set
set1 = set()
# Creating a Set of String
set1 = set("Python Programming")
print(set1)
# Creating a Set of List
set1 = set(["Computer", "Programming", "Python"])
print(set1)

Output:
{'i', 'y', ' ', 'o', 'g', 'a', 'h', 'm', 'r', 'P', 't', 'n'}
{'Programming', 'Computer', 'Python'}

Adding elements: Using add() and update():

# Python program to demonstrate Addition of elements in a Set


set1 = set()
# Adding to the Set using add()
set1.add(8)
set1.add((6, 7))
print(set1)
# Addition to the Set using Update()
set1.update([10, 11])
print(set1)

Output:
{8, (6, 7)}
{8, 10, 11, (6, 7)}

Accessing a Set:
One can loop through the set items using a for loop as set items cannot be accessed by
referring to an index.

# Python program to demonstrate Accessing of elements in a set


# Creating a set
set1 = set(["Computer", "Programming", "Python"])
# Accessing using for loop
for i in set1:
print(i, end =" ")

Output:
Computer Programming

Removing elements from a set: Using remove(), discard(), pop() and clear():

# Python program to demonstrate Deletion of elements in a Set


set1 = set([1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12])
# using Remove() method
set1.remove(5)
set1.remove(6)
print(set1)
# using Discard() method
set1.discard(8)
set1.discard(9)
print(set1)
# using the pop() method
set1.pop()
print(set1)
# using clear() method
set1.clear()
print(set1)

Output:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
{1, 2, 3, 4, 7, 10, 11, 12}
{2, 3, 4, 7, 10, 11, 12}
set( )

Dictionary
 Dictionary in Python is an unordered collection of data values, used to store data
values like a map.
 Dictionary holds key:value pair.
 Each key-value pair in a Dictionary is separated by a colon :, whereas each key is
separated by a ‘comma’.
 A Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’.

# Python program for creating an empty Dictionary


Dict = {}
print(Dict)

# with Integer Keys


Dict = {1: 'Computer', 2: 'Programming', 3: 'Python'}
print(Dict)
# with Mixed keys
Dict = {'Name': 'Python', 1: [1, 2, 3, 4]}
print(Dict)
(Run on IDE)

Output:
{}
{1: 'Computer', 2: 'Programming', 3: 'Python'}
{1: [1, 2, 3, 4], 'Name': 'Python'}

Decision Making:
 Decision Making in programming is similar to decision making in real life.
 A programming language uses control statements to control the flow of execution of
the program based on certain conditions.
 These are used to cause the flow of execution to advance and branch based on
changes to the state of a program.

Decision-making statements in Python:

 if statement
 if..else statements
 nested if statements
 if-elif ladder

Example 1: To demonstrate if and if-else


# Python program to demonstrate decision making
a = 10
b = 15
# if to check even number
if a % 2 == 0:
print("Even Number")
# if-else to check even or odd
if b % 2 == 0:
print("Even Number")
else:
print("Odd Number")

Output:
Even Number
Odd Number

#Python program To demonstrate if and if-else

# If else Statement in python


'''
Write a program to check vote eligibility by enter his/her name and age
'''
name = input("Enter your Name:")
age = int(input("Enter your Age:"))
if age >= 18:
print(name, " age is", age," so he is eligible for voting")
else:
print(name, " age is", age," so he is not eligible for voting")

output :

Enter your Name:Ram


Enter your Age:20
Ram age is 20 so he is eligible for voting

Example 2: To demonstrate nested-if and if-elif


# Python program to demonstrate decision making
a = 10
# Nested if to check whether a number is divisible by both 2 and 5
if a % 2 == 0:
if a % 5 == 0:
print("Number is divisible by both 2 and 5")

# if-elif
if (a == 11):
print ("a is 11")
elif (a == 10):
print ("a is 10")
else:
print ("a is not present")

Output:
Number is divisible by both 2 and 5
a is 10

# Python program to demonstrate decision making and nested if-else

# Nested if statement

mark1 = int(input("Enter mark1:"))


mark2 = int(input("Enter mark2:"))
mark3 = int(input("Enter mark3:"))
total = mark1 + mark2 + mark3
print("Your Total mark is ", total)
average = total / 3.0
print("Your average mark is ", average)
if mark1 >= 35 and mark2 >= 35 and mark3 >= 35:
print("\nResult:You are pass")
if average >= 90 and average <= 100:
print("You are pass with 'A' Grade")
elif average >= 80 and average < 90:
print("You are pass with 'B' Grade")
elif average >= 70 and average < 80:
print("You are pass with 'C' Grade")
else:
print("You are pass with 'D' Grade")
else:
print("You are fail")
print("Result:No grade")

output :

Enter mark1:90
Enter mark2:96
Enter mark3:97
Your Total mark is 283
Your average mark is 94.33333333333333

Result : You are pass


You are pass with 'A' Grade

Control flow (Loops):


Loops in programming come into use when we need to repeatedly execute a block of
statements.
For example:
 Suppose we want to print “Hello World” 10 times.
 This can be done with the help of loops. The loops in Python are:

While and while-else loop:


# Python program to illustrate while and while-else loop
i=0
while (i < 3):
i=i+1
print("Hello Friends")
i = 10
while i < 12:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")

Output:
Hello Friends
Hello Friends
Hello Friends
Hello Friends
11
For and for-else loop:
# Python program to illustrate Iterating over a list
print("List Iteration")
l = ["computer", "programming", "python"]
for i in l:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Python"
for i in s :
print(i)

print("\nFor-else loop")
for i in s:
print(i)
else: # Executed because no break in for
print("No Break\n")

for i in s:
print(i)
break
else: # Not executed as there is a break
print("No Break")

Output:
List Iteration
computer
programming
python

String Iteration
P
y
t
h
o
n

For-else loop
P
y
t
h
o
n
No Break

For and for-else loop:

#while else
i=1
while i<=5:
print(i)
i+=1
else:
print("While else loop is completed")
print("===================================================")
j=1
while j<=5:
if(j==4):
break
print(j)
j+=1
else:
print("While else loop is completed")
print("====================================================")
for i in range(0,20,2):
print(i)
else:
print("For loop is completed")
print("====================================================")
for i in range(0,20,2):
if(i==8):
break
print(i)
else:
print("For loop is completed")

output :

1
2
3
4
5
While else loop is completed
===================================================
1
2
3
====================================================
0
2
4
6
8
10
12
14
16
18
For loop is completed
====================================================
0
2
4
6
====================================================

range() function: range() allows user to generate a series of numbers within a given range.
Depending on how many arguments user is passing to the function. This function takes three
arguments.
1) start: integer starting from which the sequence of integers is to be returned
2) stop: integer before which the sequence of integers is to be returned.
3) step: integer value which determines the increment between each integer in the sequence
filter_none

PythonRange

# Python program to demonstrate range() function:


for i in range(5):
print(i, end =" ")
print()
for i in range(2, 9):
print(i, end =" ")
print()
# incremented by 3
for i in range(15, 25, 3):
print(i, end =" ")
(Run on IDE)

Output:
01234
2345678
15 18 21 24

Understanding for-loop in Python


Backward iteration in Python
Loop control statements
Loop control statements change execution from its normal sequence. Following are the loop
control statements provided by Python:

Break: Break statement in Python is used to bring the control out of the loop when some
external condition is triggered.
Continue: Continue statement is opposite to that of break statement, instead of terminating
the loop, it forces to execute the next iteration of the loop.
Pass: Pass statement is used to write empty loops. Pass is also used for empty control
statement, function and classes.

# Python program to demonstrate break, continue and pass:


s = 'computerprogramming'
for letter in s:
if letter == 'e' or letter == 'r':
break
print(letter, end = " ")
print()
for letter in s:
if letter == 'e' or letter == 'r':
continue
print(letter, end = " ")
print()
for letter in s:
if letter == 'e' or letter == 'r':
pass
print(letter, end = " ")

Output:
comput
computpogamming
computerprogramming

Functions

 Functions are generally the block of codes or statements in a program that gives the
user the ability to reuse the same code which ultimately saves the excessive use of
memory, acts as a time saver and more importantly, provides better readability of the
code.

 So basically, a function is a collection of statements that perform some specific task


and return the result to the caller.

 A function can also perform some specific task without returning anything. In Python,
def keyword is used to create functions.

# Python program to demonstrate functions:

Syntax:

def function_name(parameters):
statement(s)
return expression

Creating a Function
We can create a Python function using the def keyword.
def fun():
print("Welcome to SMVEC")
fun()

Output:
Welcome to SMVEC

Calling a Function
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.

Example: Python Calling Function


def fun():
print("Welcome to SMVEC")
fun()

Output:
Welcome to SMVEC

Some more examples :


def is_prime(n):
if n in [2, 3]:
return True
if n % 2 == 0:
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))

Output:
False True

# A simple Python function to check whether x is even or odd


def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd

The return statement

The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.

Syntax: return [expression_list]

The return statement can consist of a variable, an expression, or a constant which is returned
to the end of the function execution. If none of the above is present with the return statement
a None object is returned.

Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))

Output:
4
16

Function with arguments


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

# Python program to demonstrate default arguments


def myFun(x, y = 50):
print("x: ", x)
print("y: ", y)
# Driver code
myFun(10)
(Run on IDE)

Output:
('x: ', 10)
('y: ', 50)

Keyword arguments: The idea is to allow caller to specify argument name with values so
that caller does not need to remember order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname ='Computer', lastname ='Programming')
student(lastname ='Programming', firstname ='Computer')
(Run on IDE)
Output:
('Computer', 'Programming')
('Computer', 'Programming')

Variable length arguments: In Python a function can also have variable number of
arguments. This can be used in the case when we do not know in advance the number of
arguments that will be passed into a function.

The first parameter- argc (argument count)- is an integer that indicates how many
arguments were entered on the command line when the program was started.
The second parameter- argv (argument vector)- is an array of pointers to arrays of
character objects.

# Python program to demonstrate variable length arguments


# variable arguments
def myFun1(*A):
for arg in argv:
print(arg, end =" ")
# variable keyword arguments
def myFun2(**B):
for key, value in kwargs.items():
print ("% s == % s" %(key, value))

# Driver code
myFun1('Hello', 'Welcome', 'to', 'Computer Programming')
print()
myFun2(first ='Computer', mid ='Programming', last ='Python')

Output:
Hello Welcome to Computer Programming
first == Computer
last == Python
mid == Programming

Lambda functions

A lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can only have one expression.
Syntax:
lambda arguments : expression

Example:

#Add 10 to argument a, and return the result:


x = lambda a : a + 10
print(x(5))
Output:
15

 Lambda functions can take any number of arguments:


Example:
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Output:
30
Example:
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Output:
13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside
another function.
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output:
22

# Python code to demonstrate labmda function:

# Cube using lambda


cube = lambda x: x * x*x
print(cube(7))
# List comprehension using lambda
a = [(lambda x: x * 2)(x) for x in range(5)]
print(a)

Output:
343
[0, 2, 4, 6, 8]

List and Mutability:

 Mutable and immutable objects are handled differently in python.


 Immutable objects are quicker to access and are expensive to change because it
involves the creation of a copy.
 Whereas mutable objects are easy to change.
 Use of mutable objects is recommended when there is a need to change the size or
content of the object.
Exception :

 However, there is an exception in immutability as well.


 We know that tuple in python is immutable.
 But the tuple consists of a sequence of names with unchangeable bindings to objects.

Consider a tuple
tup = ([3, 4, 5], 'myname')
 The tuple consists of a string and a list.
 Strings are immutable so we can’t change its value.
 But the contents of the list can change. The tuple itself isn’t mutable but contain items
that are mutable.

Example : Add Two Numbers:

num1 = 1.5
num2 = 6.3
sum = num1 + num2
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
O/P:
The sum of 1.5 and 6.3 is 7.8

Add Two Numbers With User Input

num1 = input('Enter first number: ')


num2 = input('Enter second number: ')
sum = float(num1) + float(num2)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

O/P:
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8

Factorial of a Number using Loop


# Python program to find the factorial of a number
num = 7
# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
OUTPUT:
The factorial of 7 is 5040

UNIT II SEQUENCE DATATYPES AND OBJECT ORIENTED PROGRAMMING


Sequences – Mapping and Sets – Dictionaries. Classes: Classes and Instances – Inheritance –
Exception Handling – Introduction to Regular Expressions using “re” module.

Python Sequences

In Python programming, sequences are a generic term for an ordered set which means that
the order in which we input the items will be the same when we access them.
Python supports six different types of sequences. These
are strings, lists, tuples, byte sequences, byte arrays, and range objects. We will discuss
each of them.
Strings
String is an Immutable ie., we can not change.
Indexing:
Accessing elements in a string,
Each element is accessed using indexing, the position of each character.
Forward Indexing
Positive Indexing
Negative Indexing
Basic Operations of String:
Operators:(+,*)
1. Concatenation Operation
2. Replication Operation
Concatenation Operation:
The Concatenation operation (+) concatenate two strings and forms a new string.
Syntax:
<str_name>=<str1>+<str2>
Eg:
“python”+”programming”
o/p:
pythonprogramming
Replication Operator:
The string will be repeated the number of time which is given by the integer value.

Eg:
print(“python” *5)
o/p:
pythonpythonpythonpythonpythonpython
Membership Operator:
In:
Notin:
Syntax:
Str4 not in str1
A=‘python’
‘y’ in a
True
‘y’ not in a
False
Relational Operator:
The ASCII value of a is 97, b is 98 and so on.
The ASCII value of A is 65, B is 66 and so on.
Comparison between strings are done on the basis on ascii value.
Eg:
‘python’ == ‘python’
True
‘fruits’ == ‘fruits’
True.
Slicing:
A Segment of a string is called a slice.
String slice can be defined as substring which is the part of string.
Eg:
S=‘programming’
print(s[5:8])
o/p:
Amm
<string_name>[:end index]
Eg 1:
S=‘python programming’
Print(s[:8])
O/P:
python p
Eg 2:
S = ‘python programming’
Print (s [3:])
o/p:
hon programming
Eg 3:
print(s[:])
o/p:
python programming
String Methods in Python
1. s.capitalize() in Python
Capitalizes a string
s = "heLLo BuDdY"
s2 = s.capitalize()
print(s2)
o/p:
HELLO BUDDY.
2. s.lower() in Python
Converts all alphabetic characters to lowercase
s = "heLLo BuDdY"
s2 = s.lower()
print(s2)
Output:
hello buddy
3. s.upper() in Python
Converts all alphabetic characters to uppercase
s = "heLLo BuDdY"
s2 = s.upper()
print(s2)
Output:
HELLO BUDDY
4. s.title() in Python
Converts the first letter of each word to uppercase and remaining letters to lowercase
s = "heLLo BuDdY"
s2 = s.title()
print(s2)
Output:
Hello Buddy
5. s.swapcase() in Python
Swaps case of all alphabetic characters.
s = "heLLo BuDdY"
s2 = s.swapcase()
print(s2)
Output:
‘HEllO bUdDy’

6. s.count(<sub>[, <start>[, <end>]])


Returns the number of time <sub> occurs in s.
For Example
s = 'Dread Thread Spread'
s.count('e')
o/p:
3
s.count('rea')
o/p:
3
s.count('e', 4, 18)
o/p:
2
7. s.find(<sub>[, <start>[, <end>]])
Returns the index of the first occurrence of <sub> in s.
Returns -1 if the substring is not present in the string.
For Example
s = 'Dread Thread Spread'
s.find('Thr')
o/p:
6
s.find('rea')
o/p:
1
s.find('rea', 4, 18)
o/p:
8
s.find('x')
o/p:
-1
8. s.isalnum() in Python
Returns True if all characters of the string are alphanumeric, i.e., letters or numbers.
For Example
s = "Tech50"
>>> s.isalnum()
True
>>> s = "Tech"
>>> s.isalnum()
True
>>> s = "678"
>>> s.isalnum()
True
9. Python s.isalpha()
Returns True if all the characters in the string are alphabets.
For Example
s = "Techvidvan"
>>> s2 = "Tech50"
>>> s.isalpha()
True
>>> s2.isalpha()
False
>>>
10. Python s.isdigit()
Returns True if all the characters in the string are numbers.
For Example
>>> s1 = "Tech50"
>>> s2 = "56748"
>>> s1.isdigit()
False
>>> s2.isdigit()
True
11. s.islower()
Returns True if all the alphabets in the string are lowercase.
For Example
>>> s1 = "Tech"
>>> s2 = "tech"
>>> s1.islower()
False
>>> s2.islower()
True
>>>
12. s.isupper()
Returns True if all the alphabets in the string are uppercase.
For Example
>>> s1 = "Tech"
>>> s2 = "TECH"
>>> s1.isupper()
False
>>> s2.isupper()
True
13. s.lstrip([<chars>])
Removes leading characters from a string. Removes leading whitespaces if you don’t
provide a <chars> argument.
14. s.rstrip([<chars>])
Removes trailing characters from a string. Removes trailing whitespaces if you don’t
provide a <chars> argument.
15. s.strip([<chars>])
Removes leading and trailing characters from a string. Removes leading and trailing
whitespaces if you don’t provide a <chars> argument.
Example of lstrip(), rstrip() and strip():
>>> s = " Techvidvan "
>>> s.lstrip()
'Techvidvan '
>>> s.rstrip()
' Techvidvan'
>>> s.strip()
'Techvidvan'
>>>
16. s.join(<iterable>)
Joins elements of an iterable into a single string. Here, s is the separator string.
Example
>>> s1 = ' '.join(['We', 'are', 'Coders'])
>>> print(s1)
We are Coders
>>> s2 = ':'.join(['We', 'are', 'Coders'])
>>> print(s2)
We:are:Coders
>>>
17. s.split(sep = None, maxspit = -1)
Splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it splits
based on whitespaces.
Example
>>> l = 'we are coders'.split()
>>> l
['we', 'are', 'coders']
>>> l = 'we are coders'.split('e')
>>> l
['w', ' ar', ' cod', 'rs']

Python Lists

Python lists are similar to an array but they allow us to create a heterogeneous collection of
items inside a list. A list can contain numbers, strings, lists, tuples, dictionaries, objects,
etc.
Lists are declared by using square brackets around comma-separated items.
Syntax:
list1 = [1,2,3,4]

list2 = [‘red’, ‘green’, ‘blue’]

list3 = [‘hello’, 100, 3.14, [1,2,3] ]


Lists are mutable which makes it easier to change and we can quickly modify a list by
directly accessing it.
Code:
list = [10,20,30,40]

list[1] = 100
print( list)
Output:
[10, 100, 30, 40]
Python Tuples

Tuples are also a sequence of Python objects. A tuple is created by separating items with
a comma. They can be optionally put inside the parenthesis () but it is necessary to put
parenthesis in an empty tuple.
A single item tuple should use a comma in the end.
Code:
tup = ()

print( type(tup) )

tup = (1,2,3,4,5)

tup = ( “78 Street”, 3.8, 9826 )

print(tup)
Output:
<class ‘tuple’>
(’78 Street’, 3.8, 9826)
Tuples are also immutable like strings so we can only reassign the variable but we
cannot change, add or remove elements from the tuple.
Code:
tup = (1,2,3,4,5)

tup[2] = 10
Output:
Traceback (most recent call last):
File “<stdin>”, line 2, in <module>
TypeError: ‘tuple’ object does not support item assignment
Bytes Sequences in Python

The bytes() function in Python is used to return an immutable bytes sequence. Since they
are immutable, we cannot modify them.
If you want a mutable byte sequence, then it is better to use byte arrays. This is how we
can create a byte of a given integer size.
Code:
size = 10

b = bytes(size)

print( b )
Output:
b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′
Iterables can be converted into bytes.
Code:
print( bytes([4,2,1]) )
Output:
b’\x04\x02\x01′
For strings, we have to provide the encoding in the second parameter.
Code:
bytes(“Hey”, ‘utf=8’)
Output:
b’Hey’
Byte Arrays in Python

Byte arrays are similar to bytes sequence. The only difference here is that byte arrays
are mutable while bytes sequences are immutable. So, it also returns the bytes object the
same way.
Code:
print( bytearray(4) )

print( bytearray([1, 2, 3, 4]) )

print( bytearray(‘Hola!’, ‘utf-8’))


Output:
bytearray(b’\x00\x00\x00\x00′)
bytearray(b’\x01\x02\x03\x04′)
bytearray(b’Hola!’)
Since byte arrays are mutable, let’s try changing a byte from the array.
Code:
a = bytearray([1,3,4,5])

print(a)

a[2] = 2

print(a)
Output:
bytearray(b’\x01\x03\x04\x05′)
bytearray(b’\x01\x03\x02\x05′)

Python map() Function


map() function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
You can pass one or more iterable to the map() function.
Eg:
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
We can also use lamda expression with map to achieve above result.
Eg:
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
o/p:
[2, 4, 6, 8]
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))
o/p: [5, 7, 9]
# List of strings
l = ['sat', 'bat', 'cat', 'mat']

# map() can listify the list of strings individually


test = list(map(list, l))
print(test)
o/p
[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
Definition and Usage
The map() function executes a specified function for each item in an iterable. The item is sent
to the function as a parameter.
Syntax
map(function, iterables)
Python map() Function
❮ Built-in FunCalculate the length of each word in the tuple:
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x)
#convert the map into a list, for readability:
print(list(x))
o/p:
<map object at 0x056D44F0>
[5, 6, 6]
Example
Make new fruits by sending two iterable objects into the function:
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
print(x)
#convert the map into a list, for readability:
print(list(x))
<map object at 0x034244F0>
['appleorange', 'bananalemon', 'cherrypineapple']
Python filter() Function:
Definition and Usage
The filter() function returns an iterator were the items are filtered through a function to test if
the item is accepted or not.
Syntax
filter(function, iterable)
Example
Make new fruits by sending two iterable objects into the function:
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x) o/p:
18
24
32
Set

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been
created.

Once a set is created, you cannot change its items, but you can remove items and add new
items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types

Set items can be of any data type:

Example
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

Example

A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}


type()

From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>
Example

What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))
The set() Constructor

It is also possible to use the set() constructor to make a set.

Example

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)
Python Dictionaries
Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Example
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

Example

Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example

Duplicate values will overwrite existing values:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example

Print the number of items in the dictionary:

print(len(thisdict))
Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example

String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict':

<class 'dict'>
Example

Print the data type of a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Classes and Instances
Python is an object-oriented language and everything in it is an object.
A class is like a blueprint for objects – it has no values itself. It is an abstract data type.
We can have multiple objects of one class.
Defining a Class in Python
To define a class, we use the class keyword, not the def keyword we used to define
functions.
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values.
An object consists of :
• State: It is represented by the attributes of an object. It also reflects the properties of
an object.
• Behavior: It is represented by the methods of an object. It also reflects the response
of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Object Creation:
Syntax:
Object_name=class_name()
Declaring an object –
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
The self
• Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it.
• If we have a method that takes no arguments, then we still have to have one argument.
_init__ method:
The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initializing the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions) that are
executed at the time of Object creation.
It runs as soon as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
O/P:
Hello, my name is Nikhil
Class and Instance Variables
 Instance variables are for data, unique to each instance and class variables are for
attributes and methods shared by all instances of the class.
 Instance variables are variables whose value is assigned inside a constructor or method
with self whereas class variables are variables whose value is assigned in the class.
# Python3 program to show that we can create
# instance variables inside methods
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed):
# Instance Variable
self.breed = breed
# Adds an instance variable
def setColor(self, color):
self.color = color
# Retrieves instance variable
def getColor(self):
return self.color
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from
another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Inheritance is the capability of one class to derive or inherit the properties from another class.
The benefits of inheritance are:

1. It represents real-world relationships well.

2. It provides reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.

3. It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()
Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from
the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to
the class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
x.printname().
Python Errors and Built-in Exceptions
A python program terminates as soon as it encounters an unhandled error. These errors can be
broadly classified into two classes:
1. Syntax errors
2. Logical errors (Exceptions)
Python Syntax Errors
Error caused by not following the proper structure (syntax) of the language is called syntax
error or parsing error.
Example:
if a < 3
File "<interactive input>", line 1
if a < 3
o/p:
^
SyntaxError: invalid syntax
As shown in the example, an arrow indicates where the parser ran into the syntax error.
We can notice here that a colon : is missing in the if statement.
Python Logical Errors (Exceptions)
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical
errors.

Python Built-in Exceptions

 We can handle these built-in and user-defined exceptions in Python using try, except
and finally statements.
 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Exception Handling:
 Handling error at run time to avoid crash in a program.
 When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
 These exceptions can be handled using the try statement:
Example
 The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
 Since the try block raises an error, the except block will be executed.
 Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
print(x)
try:
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))
result = numerator/denominator
print(result)
except:
print("Denominator cannot be 0. Try again.")
print("Program ends")
Output
Enter numerator: 3
Enter denominator: 0
Denominator cannot be 0. Try again.
Program ends
Enter numerator: 3
Enter denominator: 4
0.75
Program ends
Handling Specific Exception
 Now the except block is handling only the ZeroDivisionError.
 This is mostly useful if the code inside try block can raise more than one exception.
try:
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))
result = numerator/denominator
print(result)
my_list = [1, 2, 3]
i = int(input("Enter index: "))
print(my_list[i])
except ZeroDivisionError:
print("Denominator cannot be 0. Try again.")
except IndexError:
print("Index is wrong.")
print("Program ends")
Output
Enter numerator: 6
Enter denominator: 5
1.2
Enter index: 4
Index is wrong.
Program ends
Here, there is no ZeroDivisionError, so except ZeroDivisionError block was skipped. If
there was ZeroDivisionError:
Enter numerator: 3
Enter denominator: 0
Denominator cannot be 0. Try again.
Program ends
Python try...finally
A try statement can also have an optional finally block which is executed regardless of
whether an exception occurs or not.
Its syntax looks something like this:
try:
print(1/0)
except:
print("Wrong denominator")
finally:
print("Always printed")
Output
Wrong denominator
Always printed
 The code gives the ZeroDivisionError so the except block is executed. Finally, the
code inside the finally block is also executed.
 However, if an exception doesn't occur in the try block, the except block is skipped
but finally block is still executed at the end.
Introduction to regular expression using “re” module
 A RegEx, or Regular Expression, is a sequence of characters that forms a search
pattern.
 RegEx can be used to check if a string contains the specified search pattern.
 RegEx Module
 re is a module
 It is a collection of pre-defined functions
 To process the input text.

Syntax:
import re.

RegEx Functions:
Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match


anywhere in the string

split Returns a list where the string has been


split at each match

sub Replaces one or many matches with a


string

Metacharacters:
Metacharacters are characters with a special meaning:

findall() Function
 The findall() function returns a list containing all matches.
 The list contains the matches in the order they are found.
 If no matches are found, an empty list is returned.

Example
Print a list of all matches:
import re
#Return a list containing every occurrence of "ai":
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
O/P:
['ai', 'ai']
Eg:
import re
txt = "The rain in Spain"
#Check if "Portugal" is in the string:
x = re.findall("Portugal", txt)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
O/P:
[]
No match
search() Function:
The search() function searches the string for a match, and returns a Match object if
there is a match.
If there is more than one match, only the first occurrence of the match will be
returned:

Example
Search for the first white-space character in the string:
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
O/P:
The first white-space character is located in position: 3
If no matches are found, the value None is returned:
import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)
o/p:
None
split() Function
The split() function returns a list where the string has been split at each match:
Example
Split at each white-space character:
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
o/p:
['The', 'rain', 'in', 'Spain’]
You can control the number of occurrences by specifying the maxsplit parameter:
Example:
Split the string only at the first occurrence:
import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)
o/p:
['The', 'rain in Spain']
sub() Function
The sub() function replaces the matches with the text of your choice:
Example
Replace every white-space character with the number 9:
import re
#Replace all white-space characters with the digit "9":
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
o/p:
The9rain9in9Spain
You can control the number of replacements by specifying the count parameter:
Example
Replace the first 2 occurrences:
import re
#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
o/p:
The9rain9in Spain
Match Object
A Match Object is an object containing information about the search and the result.

Note: If there is no match, the value None will be returned, instead of the Match
Object.

Example
Do a search that will return a Match Object:
import re
#The search() function returns a Match object:
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x)
o/p:
<_sre.SRE_Match object; span=(5, 7), match='ai'>
The Match object has properties and methods used to retrieve information about the
search, and the result:
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function.
.group() returns the part of the string where there was a match
Example
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case "S":
import re
#Search for an upper case "S" character in the beginning of a word, and print
its position:
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
o/p:
(12, 17)
Example
Print the string passed into the function:
import re
#The string property returns the search string:
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
o/p:
The rain in Spain
Example
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case "S":
import re
#Search for an upper case "S" character in the beginning of a word, and print the
word:
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
o/p:Spain
UNIT – III USING NUMPY
Basics of NumPy – Computation on NumPy – Aggregations – Computation on Arrays –
Comparisons – Masks and Boolean Arrays – Fancy Indexing – Sorting Arrays –
Structured Data: NumPy’s Structured Array.
What is NumPy?
 NumPy is a Python library used for working with arrays.
 It also has functions for working in domain of linear algebra, fourier
transform, and matrices.
 NumPy was created in 2005 by Travis Oliphant. It is an open source project
and you can use it freely.
 NumPy stands for Numerical Python.
Why Use NumPy?
 In Python we have lists that serve the purpose of arrays, but they are slow to
process.
 NumPy aims to provide an array object that is up to 50x faster than
traditional Python lists.
 The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
 Arrays are very frequently used in data science, where speed and resources
are very important.
Why is NumPy Faster Than Lists?
 NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
 This behavior is called locality of reference in computer science.
 This is the main reason why NumPy is faster than lists. Also it is optimized
to work with latest CPU architectures.
Installation of NumPy:

C:\Users\Your Name>pip install


numpy
Syntax:
Import NumPy
Example:
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)

o/p:
[1 2 3 4 5]

Computation on NumPy:
NumPy as np:
import numpy as np
Example:
import numpy as np
print(np.__version__)

o/p:
1.16.3

Dimensions in Arrays:
 A dimension in arrays is one level of array depth (nested arrays).
0-D Arrays:
 0-D arrays, or Scalars, are the elements in an array. Each value in an array is
a 0-D array.
Eg:
import numpy as np
arr = np.array(42)
print(arr)
o/p:
42
1-D Arrays:
 An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.
 These are the most common and basic arrays.
Eg:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

o/p:
[1 2 3 4 5]
2-D Arrays:
 An array that has 1-D arrays as its elements is called a 2-D array.
 These are often used to represent matrix or 2nd order tensors.
Eg:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

o/p:
[[1 2 3]
[4 5 6]]
3-D arrays:
Eg:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]],
[[1, 2, 3], [4, 5, 6]]])
print(arr)
o/p:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]

Check Number of Dimensions?


import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

o/p:
0
1
2
3

Arrays in NumPy:
# Python program to demonstrate basic array characteristics
import numpy as np
arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Creating array object
print("Array is of type: ", type(arr)) # Printing type of arr object
print("No. of dimensions: ", arr.ndim) # Printing array dimensions (axes)
print("Shape of array: ", arr.shape) # Printing shape of array
print("Size of array: ", arr.size) # Printing size (total number of elements) of
array
print("Array stores elements of type: ", arr.dtype) # Printing type of elements
in array

o/p:
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64

NumPy Creating Arrays:


Create a NumPy ndarray Object:
 NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
 We can create a NumPy ndarray object by using the array() function.
Eg:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

o/p:
[1 2 3 4 5]
<class 'numpy.ndarray'>
Ndarry:
 NumPy’s array class is called ndarray. It is also known by the alias array.
 To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray
Computation on Arrays :
Arrays in Numpy:
 Array in Numpy is a table of elements (usually numbers), all of the same
type, indexed by a tuple of positive integers.
 In Numpy, number of dimensions of the array is called rank of the array.
 A tuple of integers giving the size of the array along each dimension is
known as shape of the array. An array class in Numpy is called as ndarray.
 Elements in Numpy arrays are accessed by using square brackets and can be
initialized by using nested Python Lists.
# Python program for Creation of Arrays
import numpy as np
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)
arr = np.array([[1, 2, 3],[4, 5, 6]])
print("Array with Rank 2: \n", arr)
arr = np.array((1, 3, 2))
print("\nArray created using " "passed tuple:\n", arr)

o/p:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3] [4 5 6]]
Array created using passed tuple:
[1 3 2]
Accessing the array Index:
 In a numpy array, indexing or accessing the array index can be done in
multiple ways. To print a range of an array, slicing is done.
 Slicing of an array is defining a range in a new array which is used to print a
range of elements from the original array.
 Since, sliced array holds a range of elements of the original array, modifying
content with the help of sliced array modifies the original array content.
# Python program to demonstrate indexing in numpy array
import numpy as np
arr = np.array([[-1, 2, 0, 4],[4, -0.5, 6, 0],[2.6, 0, 7, 8],[3, -7, 4,2.0]])
print("Initial Array: ")
print(arr)
sliced_arr = arr[:2, ::2]
print ("Array with first 2 rows and alternate columns(0 and 2):\n",
sliced_arr)
Index_arr = arr[[1, 1, 0, 3], [3, 2, 1, 0]]
print ("\nElements at indices (1, 3), (1, 2), (0, 1), (3, 0):\n", Index_arr)

o/p:
Initial Array:
[[-1. 2. 0. 4. ]
[ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[ 3. -7. 4. 2. ]]
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[0. 6. 2. 3.]
Basic Array Operations:
# Python program to demonstrate basic operations on single array
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
print ("Adding 1 to every element:", a + 1)
print ("\nSubtracting 2 from each element:", b - 2)
print ("\nSum of all array elements: ", a.sum())
print ("\nArray sum:\n", a + b)

o/p:
Adding 1 to every element:
[[2 3]
[4 5]]
Subtracting 2 from each element:
[[ 2 1]
[ 0 -1]]
Sum of all array elements: 10 Array sum:
[[5 5]
[5 5]]

Indexing using index arrays:


Eg:
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
arr = x[np.array([1, 3, -3])]
print("\n Elements are : \n",arr)

o/p:
Elements are: [2 4 7]
Array Indexing:
 The basics of array indexing is important for analysing and manipulating the
array object.
 NumPy offers many ways to do array indexing.
Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array.
Integer array indexing: In this method, lists are passed for indexing for each
dimension. One to one mapping of corresponding elements is done to construct
a new arbitrary array.
Boolean array indexing: This method is used when we want to pick elements
from array which satisfy some condition.
Types of Indexing
There are two types of indexing :
1. Basic Slicing and indexing
2. Advanced indexing
 Purely integer indexing
 Boolean Indexing
Basic Slicing:
1. a slice object that is of the form start : stop : step
2. an integer
3. or a tuple of slice objects and integers
# Python program for indexing using basic slicing with ellipsis
import numpy as np
# A 3 dimensional array.
b = np.array([[[1, 2, 3],[4, 5, 6]],
[[7, 8, 9],[10, 11, 12]]])
print(b[...,1]) #Equivalent to b[: ,: ,1 ]
o/p:
[[ 2 5] [ 8 11]]
2. Advanced indexing :
Advanced indexing is triggered when obj is :
• an ndarray of type integer or Boolean
• or a tuple with at least one sequence object
• is a non tuple sequence object
Purely integer indexing : When integers are used for indexing.
Each element of first dimension is paired with the element of the second
dimension.
So the index of the elements in this case are (0,0),(1,0),(2,1) and the
corresponding elements are selected.
# Python program showing advanced indexing
import numpy as np
a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])
print(a[[0 ,1 ,2 ],[0 ,0 ,1]])

o/p:
[1 3 6]
Boolean Indexing:
 This indexing has some boolean expression as the index.
 Those elements are returned which satisfy that Boolean expression.
 It is used for filtering the desired element values.
# You may wish to select numbers greater than 50
import numpy as np
a = np.array([10, 40, 80, 50, 100])
print(a[a>50])

o/p:
[80 100]

#Python program to demonstrate array creation techniques


import numpy as np
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
c = np.zeros((3, 4))
print ("\nAn array initialized with all zeros:\n", c)
d = np.full((3, 3), 6, dtype = 'complex')
print ("\nAn array initialized with all 6s,Array type is
complex:\n", d)
e = np.random.random((2, 2))
print ("\nA random array:\n", e)
f = np.arange(0, 30, 5)
print ("\nA sequential array with steps of 5:\n", f)
g = np.linspace(0, 5, 10)
print ("\nA sequential array with 10 values between 0 and
5:\n", g)
arr = np.array([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])
newarr = arr.reshape(2, 2, 3)
print ("\nOriginal array:\n", arr)
print ("Reshaped array:\n", newarr)
arr = np.array([[1, 2, 3], [4, 5, 6]])
flarr = arr.flatten()
print ("\nOriginal array:\n", arr)
print ("Fattened array:\n", flarr)

o/p:
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

An array initialized with all zeros:


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

An array initialized with all 6s,Array type is complex:


[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]

A random array:
[[0.40624837 0.90527585]
[0.65387163 0.57531329]]

A sequential array with steps of 5:


[ 0 5 10 15 20 25]
A sequential array with 10 values between 0 and 5:
[0. 0.55555556 1.11111111 1.66666667 2.22222222
2.77777778
3.33333333 3.88888889 4.44444444 5. ]

Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
Reshaped array:
[[[1 2 3]
[4 5 2]]

[[4 2 1]
[2 0 1]]]

Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]

# Python program to demonstrate indexing in numpy


import numpy as np
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate columns(0 and
2):\n", temp)
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),(3, 0):\n",
temp)
cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)

o/p:
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]
Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):
[ 4. 6. 0. 3.]
Elements greater than 0:
[ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]

Basic operations:
# Python program to demonstrate basic operations on single array:
import numpy as np
a = np.array([1, 2, 5, 3])
print ("Adding 1 to every element:", a+1)
print ("Subtracting 3 from each element:", a-3)
print ("Multiplying each element by 10:", a*10)
print ("Squaring each element:", a**2)
a *= 2
print ("Doubled each element of original array:", a)
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)

o/p:
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]
Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]

Sorting array:
# Python program to demonstrate sorting in numpy:
import numpy as np
a = np.array([[1, 4, 2], [3, 4, 6],[0, -1, 5]])
print ("Array elements in sorted order:\n", np.sort(a, axis = None))
print ("Row-wise sorted array:\n", np.sort(a, axis = 1))
print ("Column wise sort by applying merge-sort:\n", np.sort(a, axis = 0,
kind = 'mergesort'))
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),('Pankaj', 2008, 7.9),
('Aakash', 2009, 9.0)]
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",np.sort(arr, order = 'name'))
print ("Array sorted by graduation year and then cgpa:\n",np.sort(arr,
order = ['grad_year', 'cgpa']))

o/p:

Array elements in sorted order:


[-1 0 1 2 3 4 4 5 6]
Row-wise sorted array:
[[ 1 2 4]
[ 3 4 6]
[-1 0 5]]
Column wise sort by applying merge-sort:
[[ 0 -1 2]
[ 1 4 5]
[ 3 4 6]]

Array sorted by names:


[(b'Aakash', 2009, 9. ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Pankaj', 2008, 7.9)]
Array sorted by graduation year and then cgpa:
[(b'Pankaj', 2008, 7.9) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Aakash', 2009, 9. )]

Numpy Functions:
Mathematical Function:
 NumPy contains a large number of various mathematical operations.
 NumPy provides standard trigonometric functions, functions for arithmetic
operations, handling complex numbers, etc.

Trigonometric Functions:

FUNCTION DESCRIPTION

tan() Compute tangent element-wise.

arcsin() Inverse sine, element-wise.

arccos() Trigonometric inverse cosine, element-wise.

arctan() Trigonometric inverse tangent, element-wise.

arctan2() Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

degrees() Convert angles from radians to degrees.

rad2deg() Convert angles from radians to degrees.

deg2rad Convert angles from degrees to radians.

radians() Convert angles from degrees to radians.

hypot() Given the “legs” of a right triangle, return its hypotenuse.

unwrap() Unwrap by changing deltas between values to 2*pi complement.


# Python program explaining sin() function
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
Sin_Values = np.sin(in_array)
print ("\nSine values : \n", Sin_Values)
o/p:
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Sine values :
[ 0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e16]

# Python program explaining cos() function


import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
cos_Values = np.cos(in_array)
print ("\nCosine values : \n", cos_Values)

o/p:
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Cosine values :
[ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -
1.00000000e+00]
Numpy | Sorting, Searching and Counting:
Sorting:
 Sorting refers to arranging data in a particular format.
 Sorting algorithm specifies the way to arrange data in a particular order.
 Most common orders are in numerical or lexicographical order.
 In Numpy, we can perform various sorting operations using the various
functions that are provided in the library like sort, lexsort, argsort etc.
numpy.sort() : This function returns a sorted copy of an array.

#Python code to demonstrate numpy sort


import numpy as np
# sort along the first axis
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1)
# sort along the last axis
a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong last axis : \n", arr2)
# sort along not a specified axis
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)

o/p:
Along first axis :
[[10 1]
[12 15]]
Along last axis :
[[10 15]
[ 1 12]]
Along none axis :
[ 1 10 12 15]

numpy.argsort() : This function returns the indices that would sort an array.
# Python code to demonstrate working of numpy.argsort
import numpy as np
a = np.array([9, 3, 1, 7, 4, 3, 6])
print('Original array:\n', a)
b = np.argsort(a)
print('Sorted indices of original array->', b)
c = np.zeros(len(b), dtype = int)
for i in range(0, len(b)):
c[i]= a[b[i]]
print('Sorted array->', c)

o/p:
Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]

Searching:
 Searching is an operation or a technique that helps finds the place of a given
element or value in the list.
 In Numpy, we can perform various searching operations using the various
functions that are provided in the library like argmax, argmin, nanaargmax
etc.
numpy.argmax() : This function returns indices of the max element of the array in
a particular axis.
# Python Program illustrating working of argmax()
import numpy as np
array = np.arange(12).reshape(3, 4)
print("INPUT ARRAY : \n", array)
print("\nMax element : ", np.argmax(array))
print(("\nIndices of Max element : ", np.argmax(array, axis=0)))
print(("\nIndices of Max element : ", np.argmax(array, axis=1)))

o/p:
INPUT ARRAY :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Max element : 11
Indices of Max element : [2 2 2 2]
Indices of Max element : [3 3 3]

numpy.argmin() : This function returns the indices of the minimum values along
an axis.
# Python Program illustrating working of argmin()
import numpy as np
array = np.arange(8)
print("INPUT ARRAY : \n", array)
print("\nIndices of min element : ", np.argmin(array, axis=0))

o/p:
INPUT ARRAY :
[0 1 2 3 4 5 6 7]
Indices of min element : 0

Counting:
numpy.count_nonzero() : Counts the number of non-zero values in the array.
# Python Program illustrating working of count_nonzero()
import numpy as np
arr = [[0, 1, 2, 3, 4], [5, 0, 6, 0, 7]]
gf = np.count_nonzero(arr)
print(gf)
gfg = np.count_nonzero(arr, axis = 0)
print (gfg)
o/p:
7
[1 1 2 1 2]

Random sampling in numpy | randint() function:


 numpy.random.randint() -is one of the function for doing random
sampling in numpy.
 It returns an array of specified shape and fills it with random integers from
low (inclusive) to high (exclusive), i.e. in the interval [low, high).
Syntax :
numpy.random.randint(low, high=None, size=None, dtype=’l’)

# Python program explaining numpy.random.randint() function


import numpy as np
out_arr = np.random.randint(low = 0, high = 3, size = 5)
out_arr1 = np.random.randint(low = 4, size =(2, 3))
out_arr2 = np.random.randint(2, 10, (2, 3, 4))
print ("Output 1D Array filled with random integers : ", out_arr)
print ("Output 2D Array filled with random integers : ", out_arr1)
print ("Output 3D Array filled with random integers : ", out_arr2)
o/p:
Output 1D Array filled with random integers : [1 1 0 1 1]
Output 2D Array filled with random integers : [[1 1 0]
[1 0 3]]
Output 3D Array filled with random integers :
[[[4 8 5 7]
[6 5 6 7]
[4 3 4 3]]

[[2 9 2 2]
[3 2 2 3]
[6 8 3 2]]]

Random sampling in numpy | random_sample() function:


 numpy.random.random_sample()-is one of the function for doing random
sampling in numpy.
 It returns an array of specified shape and fills it with random floats in the
half-open interval [0.0, 1.0).
Syntax :
numpy.random.random_sample(size=None)

# Python program explaining numpy.random.sample() function


import numpy as np
out_val = np.random.random_sample()
out_arr = np.random.random_sample(size =(1, 3))
out_arr1 = np.random.random_sample((3, 2, 1))
print ("Output random float value : ", out_val)
print ("Output 2D Array filled with random floats : ", out_arr)
print ("Output 3D Array filled with random floats : ", out_arr1)

o/p:
Output random float value : 0.9211987310893188
Output 2D Array filled with random floats : [[ 0.64325146 0.4699456
0.89895437]]
Output 3D Array filled with random floats : [[[ 0.78245025]
[ 0.77736746]]

[[ 0.54389267]
[ 0.18491758]][[ 0.97428409]
[ 0.73729256]]]

Random sampling in numpy | ranf() function:


 numpy.random.ranf()-is one of the function for doing random sampling in
numpy.
 It returns an array of specified shape and fills it with random floats in the
half-open interval [0.0, 1.0).
Syntax :
numpy.random.ranf(size=None)

# Python program explaining numpy.random.ranf() function


import numpy as np
out_val = np.random.ranf()
out_arr = np.random.ranf(size =(2, 1))
out_arr1 = np.random.ranf((3, 3, 2))
print ("Output random float value : ", out_val)
print ("Output 2D Array filled with random floats : ", out_arr)
print ("Output 3D Array filled with random floats : ", out_arr)
o/p:
Output random float value : 0.0877051588430926
Output 2D Array filled with random floats : [[ 0.14186407]
[ 0.58068259]]
Output 3D Array filled with random floats : [[[ 0.11013584 0.67844746]
[ 0.84691569 0.09467084]
[ 0.69918864 0.12137178]]

[[ 0.30629051 0.28301093]
[ 0.1302665 0.2196221 ]
[ 0.51555358 0.73191852]]

[[ 0.72806359 0.66485275]
[ 0.80654791 0.04947181]
[ 0.06380535 0.99306064]]]
Random sampling in numpy | random_integers() function:
 numpy.random.random_integers()-is one of the function for doing
random sampling in numpy.
 It returns an array of specified shape and fills it with random integers from
low (inclusive) to high (exclusive), i.e. in the interval [low, high).
Syntax:
numpy.random.random_integers(low, high=None, size=None)

# Python program explaining numpy.random.random_integers() function


import numpy as np
out_arr = np.random.random_integers(low = 0, high = 5, size = 4)
out_arr1 = np.random.random_integers(low = 3, size =(3, 3))
out_arr2 = np.random.random_integers(1, 6, (2, 2, 3))
print ("Output 1D Array filled with random integers : ", out_arr)
print ("Output 2D Array filled with random integers : ", out_arr1)
print ("Output 3D Array filled with random integers : ", out_arr2)

o/p:
Output 1D Array filled with random integers : [1 1 4 1]
Output 2D Array filled with random integers : [[2 3 1]
[2 2 3]
[3 3 3]]
Output 3D Array filled with random integers : [[[4 8 5 7]
Output 3D Array filled with random integers : [[[5 1 5]
[5 4 1]]

[[3 6 4]
[4 5 3]]]

Fancy Indexing:
 Fancy indexing is like the simple indexing we've already seen, but we pass
arrays of indices in place of single scalars.
 This allows us to very quickly access and modify complicated subsets of an
array's values.
# For example, consider the following array:
import numpy as np
arr=np.arrange(24).reshape(6,4)
arr
o/p:
Array([0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15],
[16,17,18,19],
[20,21,22,23])

#Example Program:
Arr[[0,3,2]]

o/p:
array([0,1,2,3],
[12,13,14,15],
[8,9,10,11])

Sorting Arrays:
 Sorting means putting elements in an ordered sequence.
 Ordered sequence is any sequence that has an order corresponding to
elements, like numeric or alphabetical, ascending or descending.
 The NumPy ndarray object has a function called sort(), that will sort a
specified array.
#Example 1:
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
o/p:
[0 1 2 3]

#Sort the array alphabetically:


import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
o/p:
['apple' 'banana' 'cherry']
#Sort a 2-D array
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
o/p:
[[2 3 4]
[0 1 5]]

Structured Data: Structured Array


 Numpy’s Structured Array is similar to Struct in C.
 It is used for grouping data of different types and sizes.
 Structure array uses data containers called fields. Each data field can contain
data of any type and size.
 Array elements can be accessed with the help of dot notation.
Note: Arrays with named fields that can contain data of various types and sizes.
Properties of Structured array:
 All structs in array have same number of fields.
 All structs have same fields names.
 For example, consider a structured array of student which has different
fields like name, year, marks.

 Each record in array student has a structure of class Struct.


 The array of a structure is referred to as struct as adding any new fields for a
new struct in the array, contains the empty array.
# Python program to demonstrate Structured array
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],
dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
print(a)

o/p:
[('Sana', 2, 21.0) ('Mansi', 7, 29.0)]

 The structure array can be sorted by using numpy.sort() method and passing
the order as parameter.
 This parameter takes the value of the field according to which it is needed to
be sorted.
# Python program to demonstrate Sorting in Structured array
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],
dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
# Sorting according to the name
b = np.sort(a, order='name')
print('Sorting according to the name', b)
# Sorting according to the age
b = np.sort(a, order='age')
print('\nSorting according to the age', b)

o/p:
Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)]
Sorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)]

You might also like