Python Unit 2
Python Unit 2
Python String
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally, it
stores manipulated character as the combination of the 0's and 1's
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
String Operator
In Python, strings can be created by enclosing the character or the sequence of characters
in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to
create the string.
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the
string. However, we can use the : (colon) operator in Python to access the substring from
the given string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive
i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and
nothing else.
Definition of a class:
In any programming language, a class is a user-defined plan or blueprint using which
objects or instances of the class are created.
You may wonder why we need classes in programming. We can create something like a
variable or a structure, store what we want, and use it.
o A class can have its attributes - variables and functions with pre-stored
values and functionalities.
o Example situation: If we want to store the data of different age groups of
children and their details in an orphanage :
o We cannot just create a list and keep on storing the ages and names of the
children without any organization.
o Creating multiple lists for multiple age groups - one list to store ages, one for
names, another to match - becomes complex and leads to ambiguity.
Syntax:
#Definition of a class
1. class class_name:
2. #body of the class
3. #variables
4. #functions
5. #body of the functions
6. class" is a keyword in python libraries.
7. A class name must be capitalized.
8. Attributes are the variables owned by the class (declared inside the class) that the created
objects can use.
9. Methods are the functions owned by the class (defined inside the class) that the created
objects can use.
10. The created objects using the dot (.) operator uses these attributes and methods of a class.
Example program:
1. class Employee:
2. #Attributes like name, id
3. #Methods
Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are,
their syntax, their primary parts, return keywords, and significant types. We'll also look at
some examples of Python function definitions.
Client-characterized and worked-in capabilities are the two primary classes of capabilities
in Python. It aids in maintaining the program's uniqueness, conciseness, and structure.
Code
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming
that no worth is provided for the contention when the capability is called. The following
example demonstrates default arguments.
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a
capability with watchword contentions, the client might tell whose boundary esteem it is
by looking at the boundary name.
In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is
no limit on the number of levels up to which, the multi-level inheritance is archived in
python.
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))
Output:
True
False
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
Output:
True
Polymorphism in Python
What is polymorphism? Polymorphism refers to having multiple forms. Polymorphism is
a programming term that refers to the use of the same function name, but with different
signatures, for multiple types.
10
4
Polymorphism with Class Methods
Below is an example of how Python can use different types of classes in the same way.
For loops that iterate through multiple objects are created. Next, call the methods without
caring about what class each object belongs to. These methods are assumed to exist in
every class.
Example:
1. class xyz():
2. def websites(self):
3. print("Javatpoint is a website out of many availabe on net.")
4.
5. def topic(self):
6. print("Python is out of many topics about technology on Javatpoint.")
7.
8. def type(self):
9. print("Javatpoint is an developed website.")
10.
11. class PQR():
12. def websites(self):
13. print("Pinkvilla is a website out of many availabe on net. .")
14.
15. def topic(self):
16. print("Celebrities is out of many topics.")
17.
18. def type(self):
19. print("pinkvilla is a developing website.")
20.
21. obj_jtp = xyz()
22. obj_pvl = PQR()
23. for domain in (obj_jtp, obj_pvl):
24. domain.websites()
25. domain.topic()
26. domain.type()
Output:
Example:
1. class Birds:
2. def intro1(self):
3. print("There are multiple types of birds in the world.")
4. def flight1(self):
5. print("Many of these birds can fly but some cannot.")
6.
7. class sparrow1(Birds):
8. def flight1(self):
9. print("Sparrows are the bird which can fly.")
10.
11. class ostrich1(Birds):
12. def flight1(self):
13. print("Ostriches are the birds which cannot fly.")
14.
15. obj_birds = Birds()
16. obj_spr1 = sparrow1()
17. obj_ost1 = ostrich1()
18.
19. obj_birds.intro1()
20. obj_birds.flight1()
21.
22. obj_spr1.intro1()
23. obj_spr1.flight1()
24.
25. obj_ost1.intro1()
26. obj_ost1.flight1()
Output:
With the datetime module, you can easily perform operations on dates and times, and it
is widely used in various applications such as database operations, scheduling tasks,
working with time-series data, etc.
The datetime module in Python provides classes and functions for working with dates and
times. These classes and functions allow you to perform a wide range of operations, from
simple tasks such as formatting dates and times to more complex ones such as performing
arithmetic with dates and times or working with time zones.
This tutorial teaches us about applying the math module from fundamentals to more
advanced concepts with the support of easy examples to understand the concepts fully.
We have included the list of all built-in functions defined in this module for better
understanding.
Since the source code of this module is in the C language, it provides access to the
functionalities of the underlying C library. Here we have given some basic examples of the
Math module in Python. The examples are written below -
Program Code 1:
Here we give an example of a math module in Python for calculating the square root of a
number. The code is given below -
1. # This program will show the calculation of square root using the math module
2. # importing the math module
3. import math
4. print(math.sqrt( 9 ))
Output:
Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -
3.0
This Python module does not accept complex data types. The more complicated
equivalent is the cmath module.
We can, for example, calculate all trigonometric ratios for any given angle using the built-
in functions in the math module. We must provide angles in radians to these trigonometric
functions (sin, cos, tan, etc.). However, we are accustomed to measuring angles in terms
of degrees. The math module provides two methods to convert angles from radians to
degrees and vice versa.
Math Module:
Program code-
We use a program code to know all the functions of the Math module in Python. The code
is given below -
1. import math
2. dir(math)
Output:
Now we compile the above code in Python, and after successful compilation, we run it.
Then the output is given below -
['__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'comb',
'copysign',
'cos',
'cosh',
'degrees',
'dist',
'e',
'erf',
'erfc',
'exp',
'expm1',
'fabs',
'factorial',
'floor',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite',
'isinf',
'isnan',
'isqrt',
'ldexp',
'lgamma',
'log',
'log10',
'log1p',
'log2',
'modf',
'nan',
'perm',
'pi',
'pow',
'prod',
'radians',
'remainder',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
'tau',
'trunc']
Packages in Python
A package is considered a collection of tools that allows the programmers to initiate the
code. A Python package acts as a user-variable interface for any source code. This feature
allows a Python package to work at a defined time for any functional script in the runtime.
Example: