Python (Unit Ii)
Python (Unit Ii)
UNIT 2
String Handling, Classes, Modules and Package
2.1 Strings, String operations and String Slicing
Here, if we check the type of the variable str using a Python script.
Creating a String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
CODE;-
# Python Program for
# Creation of String
#
# Creating a String
# with single Quotes
String1 = 'Welcome to the Latur'
print("String with the use of Single Quotes: ")
print(String1)
OUTPUT:-
String with the use of Single Quotes:
Welcome to the Latur
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
2.1.2. String operations
Accessing characters in Python
CODE:-
# Python Program to Access
# characters of String
String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)
OUTPUT:-
Initial String:
HELLOCOCSITLATUR
# Updating a character
# of the String
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)
OUTPUT:-
Initial String:
Hello, I'm a AB
Traceback (most recent call last):
File "f:\COCSIT\B.Sc(CS)- TY(Python)\File_Handling\main.py", line 10, in
<module>
String1[2] = 'p'
TypeError: 'str' object does not support item assignment
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
CODE:-
# Python Program to Delete
# characters from a String
# Deleting a character
# of the String
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)
OUTPUT:-
Initial String:
Hello, I'm a AB
Traceback (most recent call last):
File "f:\COCSIT\B.Sc(CS)-
TY(Python)\File_Handling\main.py", line 10, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
OUTPUT:-
Initial String:
Hello, I'm a Geek
# Initial String
String1 = '''I'm a "AB"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print(String1)
OUTPUT:-
Initial String with use of Triple Quotes:
I'm a "AB"
Escaping Backslashes:
C:\Python\AB\
slice() Constructor
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each
index for slicing.
Return Type: Returns a sliced object containing elements in the given range
only.
Index tracker for positive and negative index:
Negative comes into considers when tracking the string in reverse.
CODE:-
# Python program to demonstrate
# string slicing
# String slicing
String ='ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This
is an easy and convenient way to slice a string both syntax wise and execution
wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.
CODE:-
# Python program to demonstrate
# string slicing
# String slicing
String ='ASTRING'
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
OUTPUT:-
AST
SR
GITA
Reverse String
GNIRTSA
Python OOPs Concepts
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Some points on Python class:
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 Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
CODE:-
class Student:
pass
In the above example, the class keyword indicates that you are creating a class
followed by the name of the class.
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. It’s not an idea anymore, it’s an actual
dog, like a dog of breed pug who’s seven years old. You can have many dogs
to create many different instances, but without the class as a guide, you would
be lost, not knowing what information is required.
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.
CODE:-
class Student:
name = "abc" #attribute1
age = 21 #attribute2
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
def myfun(self):
print(self.name)
print(self.age)
object = Student()
object.myfun()
OUTPUT:-
abc
21
__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.
CODE:-
# A Sample class with init method
class Person:
# Sample Method
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('ABC')
p.say_hi()
Output:
Hello, my name is ABC
CODE:-
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class Variable
person = 'student'
# Instance Variable
self.name = value1
self.age = value2
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
OUTPUT:-
abc
xyz
22
23
Encapsulation
CODE:-
# Python program to
# demonstrate private members
# Calling constructor of
# Base class
Base.__init__(self)
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
OUTPUT:-
HelloCocsitHello
Types of inheritance:-
Example:
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# inheritance
class Child:
# Constructor
self.name = name
# To get name
def getName(self):
return self.name
def isStudent(self):
return False
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
class Student(Child):
# True is returned
def isStudent(self):
return True
# Driver code
# An Object of Child
std = Child("Ram")
print(std.getName(), std.isStudent())
# An Object of Student
std = Student("Shivam")
print(std.getName(), std.isStudent())
Output:
Ram False
Shivam True
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Types of Inheritance in Python
Types of Inheritance depends upon the number of child and parent classes
involved. There are four types of inheritance in Python:
Example:
# single inheritance
# Base class
class Parent:
def func1(self):
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Derived class
class Child(Parent):
def func2(self):
# Driver's code
object = Child()
object.func1()
object.func2()
Output:
Multiple Inheritance: When a class can be derived from more than one base
class this type of inheritance is called multiple inheritance. In multiple
inheritance, all the features of the base classes are inherited into the derived
class.
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Example:
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
def parents(self):
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:
Father : RAM
Mother : SITA
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
further inherited into the new derived class. This is similar to a relationship
representing a child and grandfather.
Example:
# multilevel inheritance
# Base class
class Grandfather:
self.grandfathername = grandfathername
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Intermediate class
class Father(Grandfather):
self.fathername = fathername
Grandfather.__init__(self, grandfathername)
# Derived class
class Son(Father):
self.sonname = sonname
def print_name(self):
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Driver code
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance: When more than one derived classes are created
from a single base this type of inheritance is called hierarchical inheritance. In
this program, we have a parent (base) class and two child (derived) classes.
Example:
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
# Derived class1
class Child1(Parent):
def func2(self):
# Derivied class2
class Child2(Parent):
def func3(self):
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Example:
# hybrid inheritance
class School:
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
def func1(self):
class Student1(School):
def func2(self):
class Student2(School):
def func3(self):
def func4(self):
# Driver's code
object = Student3()
object.func1()
object.func2()
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Output:
This function is in school.
This function is in student 1.
Python Modules
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code. Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Example: create a simple module
return (x+y)
return (x-y)
Syntax:
import module
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
import calc
print(calc.add(10, 2))
Output:
12
# module math
# are required.
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Syntax:
from module_name import *
The use of * has its advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else do
so.
# module math
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
In Python, date and time are not a data type of their own, but a module
named datetime can be imported to work with the date as well as time. Python
Datetime module comes built into Python, so there is no need to install it
externally.
Python Datetime module supplies classes to work with date and time. These
classes provide a number of functions to deal with dates, times and time
intervals. Date and datetime are an object in Python, so when you manipulate
them, you are actually manipulating objects and not string or timestamps.
The DateTime module is categorized into 6 main classes –
date – An idealized naive date, assuming the current Gregorian calendar
always was, and always will be, in effect. Its attributes are year, month and
day.
time – An idealized time, independent of any particular day, assuming that
every day has exactly 24*60*60 seconds. Its attributes are hour, minute,
second, microsecond, and tzinfo.
datetime – Its a combination of date and time along with the attributes year,
month, day, hour, minute, second, microsecond, and tzinfo.
timedelta – A duration expressing the difference between two date, time, or
datetime instances to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – A class that implements the tzinfo abstract base class as a fixed
offset from the UTC (New in version 3.2).
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Date class
The date class is used to instantiate date objects in Python. When an object of
this class is instantiated, it represents a date in the format YYYY-MM-DD.
Constructor of this class needs three mandatory arguments year, month and
date.
Constructor syntax:
class datetime.date(year, month, day)
The arguments must be in the following range –
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
Note – If the argument is not an integer it will raise a TypeError and if it is
outside the range a ValueError will be raised.
# Python program to
# initializing constructor
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# outside range
Output:
Date passed as argument is 1996-12-11
Traceback (most recent call last):
File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in
my_date = date(1996, 12, 39)
ValueError: day is out of range for month
To return the current local date today() function of date class is used. today()
function comes with several attributes (year, month and day). These can be
printed individually.
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
# Python program to
today = date.today()
Output
Today's date is 2021-08-19
We can get the year, month, and date attributes from the date object using the
year, month and date attribute of the date class.
today = date.today()
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Output
Current year: 2021
Current month: 8
Current day: 19
date_time = datetime.fromtimestamp(1887639468)
Output
Datetime from timestamp: 2029-10-25 16:17:48
Python3
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
today = date.today()
Str = date.isoformat(today)
print(type(Str))
Output
String Representation 2021-08-19
<class 'str'>
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur