PYTHON NOTES 1,2,3
PYTHON NOTES 1,2,3
INTRODUCTION TO PYTHON
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 !”
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.
# 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.
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.
Output:
0
14
-11
14
2
40
Assignment operators: Assignment operators are used to assign values to the variables.
# Examples of Assignment operators
# 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)
Output:
Computer Programming
x=5
CPII
Python@Programming
Python Data Types:
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:
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:
[]
['Computer Programming', 'Python']
[['Computer', 'Programming'], ['Python']]
# 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']
# 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:
Example Programs:
Output:
()
('Computer', 'Program')
(1, 2, 4, 5, 6)
((0, 1, 2, 3), ('Python', 'Programming'))
Output:
1
5
Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be
reassigned to the same name.
Output:
Traceback (most recent call last):
File "/home/084519a8889e9b0103b874bbbb93e1fb.py", line 11, in
tuple1[0] = -1
TypeError: 'tuple' object does not support item assignment
Boolean
Booleans are data type with one of the two built-in values, True or False. It is denoted by the
class bool.
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’.
Output:
{'i', 'y', ' ', 'o', 'g', 'a', 'h', 'm', 'r', 'P', 't', 'n'}
{'Programming', 'Computer', 'Python'}
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.
Output:
Computer Programming
Removing elements from a set: Using remove(), discard(), pop() and clear():
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’.
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.
if statement
if..else statements
nested if statements
if-elif ladder
Output:
Even Number
Odd Number
output :
# 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
# Nested if statement
output :
Enter mark1:90
Enter mark2:96
Enter mark3:97
Your Total mark is 283
Your average mark is 94.33333333333333
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)
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
#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
Output:
01234
2345678
15 18 21 24
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.
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.
A function can also perform some specific task without returning anything. In Python,
def keyword is used to create 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.
Output:
Welcome to SMVEC
Output:
False True
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.
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.
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
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.
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.
# 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
Example:
Output:
343
[0, 2, 4, 6, 8]
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.
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
O/P:
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
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
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’
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]
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)
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(a)
a[2] = 2
print(a)
Output:
bytearray(b’\x01\x03\x04\x05′)
bytearray(b’\x01\x03\x02\x05′)
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.
* Note: Set items are unchangeable, but you can remove items and add new items.
Example
Create a Set:
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.
Example
print(thisset)
To determine how many items a set has, use the len() function.
Example
print(len(thisset))
Example
String, int and boolean data types:
Example
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
Example
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
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.
Example
To determine how many items a dictionary has, use the len() function:
Example
print(len(thisdict))
Dictionary Items - Data Types
Example
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
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:
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.
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.
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
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:
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]]]
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
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]]
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]
o/p:
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
A random array:
[[0.40624837 0.90527585]
[0.65387163 0.57531329]]
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]
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:
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
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.
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]
[[2 9 2 2]
[3 2 2 3]
[6 8 3 2]]]
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]]]
[[ 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)
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]
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)]