Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Unit 2

The document covers essential concepts of Python programming, focusing on string handling, classes, and functions. It explains string operators, class definitions, inheritance, and polymorphism, providing examples for clarity. Additionally, it discusses function arguments and the differences between pass by reference and pass by value.

Uploaded by

yogijadhav708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit 2

The document covers essential concepts of Python programming, focusing on string handling, classes, and functions. It explains string operators, class definitions, inheritance, and polymorphism, providing examples for clarity. Additionally, it discusses function arguments and the differences between pass by reference and pass by value.

Uploaded by

yogijadhav708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit II

String Handling, Classes, Modules and Package

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

It is known as concatenation operator used to join the


+
strings given either side of the operator.

It is known as repetition operator. It concatenates the


*
multiple copies of the same string.

It is known as slice operator. It is used to access the


[]
sub-strings of a particular string.

It is known as range slice operator. It is used to


[:]
access the characters from the specified range.

It is known as membership operator. It returns if a


in
particular sub-string is present in the specified string.

It is also a membership operator and does the exact


not in reverse of in. It returns true if a particular substring is
not present in the specified string.

It is used to specify the raw string. Raw strings are


used in the cases where we need to print the actual
r/R meaning of escape characters such as "C://python".
To define any string as a raw string, the character r or
R is followed by the string.
It is used to perform string formatting. It makes use of
the format specifiers used in C programming like %d
%
or %f to map their values in python. We will discuss
how formatting is done in python.

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.

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.

Consider the following example:

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.

What are Python Functions?


A collection of related assertions that carry out a mathematical, analytical, or evaluative
operation is known as a function. An assortment of proclamations called Python
Capabilities returns the specific errand. Python functions are necessary for intermediate-
level programming and are easy to define. Function names meet the same standards as
variable names do. The objective is to define a function and group-specific frequently
performed actions. Instead of repeatedly creating the same code block for various input
variables, we can call the function and reuse the code it contains with different variables.

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.

Pass by Reference vs. Pass by Value


In the Python programming language, all parameters are passed by reference. It shows
that if we modify the worth of contention within a capability, the calling capability will
similarly mirror the change. For instance,

Code

1. # Example Python Code for Pass by Reference vs. Value


2. # defining the function
3. def square( item_list ):
4. '''''''This function will find the square of items in the list'''
5. squares = [ ]
6. for l in item_list:
7. squares.append( l**2 )
8. return squares
9.
10. # calling the defined function
11. my_list = [17, 52, 8];
12. my_result = square( my_list )
13. print( "Squares of the list are: ", my_result )
Output:

Squares of the list are: [289, 2704, 64]

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.

1. Python code to demonstrate the use of default arguments


2. # defining a function
3. def function( n1, n2 = 20 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling the function and passing only one argument
8. print( "Passing only one argument" )
9. function(30)
10.
11. # Now giving two arguments to the function
12. print( "Passing two arguments" )
13. function(50,30)
Output:

Passing only one argument


number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30

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.

We can eliminate or orchestrate specific contentions in an alternate request since the


Python translator will interface the furnished watchwords to connect the qualities with its
boundaries. One more method for utilizing watchwords to summon the capability()
strategy is as per the following:
1. Python code to demonstrate the use of keyword arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30)
Output:

Without using keyword


number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.

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.

The syntax of multi-level inheritance is given below.

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...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

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

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false
otherwise.

Consider the following example.

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

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.

Consider the following example.

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.

Example of in-built polymorphic functions:

1. # Python program for demonstrating the in-built poly-morphic functions


2.
3. # len() function is used for a string
4. print (len("Javatpoint"))
5.
6. # len() function is used for a list
7. print (len([110, 210, 130, 321]))
Output:

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:

Javatpoint is a website out of many availabe on net.


Python is out of many topics about technology on Javatpoint.
Javatpoint is an developed website.
Pinkvilla is a website out of many availabe on net.
Celebrities is out of many topics.
pinkvilla is a developing website.
Polymorphism with Inheritance:
Polymorphism allows us to define methods in Python that are the same as methods in the
parent classes. In inheritance, the methods of the parent class are passed to the child
class. It is possible to change a method that a child class has inherited from its parent
class. This is especially useful when the method that was inherited from the parent doesn't
fit the child's class. We re-implement such methods in the child classes. This is Method
Overriding.

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:

There are multiple types of birds in the world.


Many of these birds can fly but some cannot.
There are multiple types of birds in the world.
Sparrows are the bird which can fly.
There are multiple types of birds in the world.
Ostriches are the birds which cannot fly.

Introduction of Datetime Modules in Python


The datetime module in Python is part of the standard library and provides classes and
functions for working with dates and times. The datetime module is especially useful for
tasks such as:

o Parsing dates and times from strings


o Formatting dates and times into strings
o Doing arithmetic with dates and times (e.g., finding the difference between two dates)
o Extracting components of dates and times (e.g., the year, month, day, hour, minute,
second, etc.)
o Representing dates and times in a time zone-aware or time zone-naive manner
The main classes in the datetime module are date, time, and datetime. The date class
represents a date (year, month, day), the time class represents a time of day (hours,
minutes, seconds, microseconds), and the datetime class represents a date and time
together. The datetime module also includes a timedelta class, which represents a
duration or the difference between two dates or times.

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.

Some of the main classes and functions provided by


the datetime module are:
1. datetime class: The datetime class represents a date and time as a single object. It has
attributes for the year, month, day, hour, minute, second, and microsecond. You can create
a datetime object by passing the year, month, day, hour, minute, second, and microsecond
as arguments to the constructor, or by using the datetime.now() method to get the current
date and time.
2. date class: The date class represents a date (year, month, day) without a time of day. You
can create a date object by passing the year, month, and day as arguments to the
constructor, or by using the datetime.date.today() method to get the current date.
3. time class: The time class represents a time of day (hours, minutes, seconds, and
microseconds) without a date. You can create a time object by passing the hours, minutes,
seconds, and microseconds as arguments to the constructor.
4. timedelta class: The timedelta class represents a duration or the difference between two
dates or times. You can use timedelta objects to perform arithmetic with dates and times,
such as finding the difference between two datetime objects, or adding or subtracting a
timedelta from a datetime object to get a new datetime.
5. tzinfo class: The tzinfo class is used to represent time zones in the datetime module. You
can use tzinfo objects to create time zone-aware datetime objects, which allow you to work
with dates and times in different time zones.
6. Formatting and parsing functions: The datetime module provides functions for
formatting and parsing dates and times as strings, such as strftime and strptime. These
functions allow you to control the format of dates and times when they are converted to or
from strings.

Python Math Module


Introduction
In this article, we are discussing Math Module in Python. We can easily calculate many
mathematical calculations in Python using the Math module. Mathematical calculations
may occasionally be required when dealing with specific fiscal or rigorous scientific tasks.
Python has a math module that can handle these complex calculations. The functions in
the math module can perform simple mathematical calculations like addition (+) and
subtraction (-) and advanced mathematical calculations like trigonometric operations and
logarithmic operations.

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.

What is Math Module in Python?


Python has a built-in math module. It is a standard module, so we do not need to install it
separately. We only must import it into the program we want to use. We can import the
module, like any other module of Python, using import math to implement the functions to
perform mathematical operations.

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.

Let us consider the following example demonstrating the package in Python.

Example:

1. # importing the package


2. import math
3. # printing a statement
4. print("We have imported the math package")
Output:

We have imported the math package


Packages
1. A Package consists of the __init__.py file for each user-oriented script. However, the
same does not apply to the modules in runtime for any script specified to the users.
2. A module is a file that contains a Python script in runtime for the code specified to the
users. A package also modifies the user interpreted code in such a manner that it gets
easily operated in the runtime.

You might also like