Python History and Versions: o o o o o o o o o o
Python History and Versions: o o o o o o o o o o
2. Python Version
Python programming language is being updated regularly with new features and supports. There are lots
of updations in python versions, started from 1994 to current release.
In this section of the tutorial, we will discuss the installation of python on various operating
systems.
The following window shows all the optional features. All the features need to be installed and
are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you want
to install and click next. Here, we must notice that the first check-box (install for all users) must
be checked.
Now we are ready to install python-3.6.7.Lets install it
To set the path on Python, we need to set the environment variable.
Add the new path variable in the user variable section.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image
.
Now the path is set, we are ready to run python on our system. Restart CMD and type python
again. It will open the python interpreter shell where we can execute the python statements.
4. Environment Variables
Environment variables are a key value pairs that can affect how a program runs. They need to be set at
some point before a process is run so the process can read them in and act accordingly. A lot of times in
production environments your database name and password are set as environment variables so that
information does not end up in a code repository somewhere.
By relying on an environment variable your code doesn't care what a setting is because you can set that at
some other point. Actually working with environment variables is really simple. All you need to st art is
import os and you are off to the races.
Python code files can be created with any plain text editor. If you are new to Python programming, you
can try Sublime Text, which is a powerful and easy-to-use editor, but you can use any editor you like.
To keep moving forward in this tutorial, you’ll need to create a test script. Open your favorite
text editor and write the following code:
1 #!/usr/bin/env python3
2
3 print('Hello World!')
Save the file in your working directory with the name hello.py. With the test script ready, you
can continue reading.
$ python3 hello.py
Hello World!
If everything works okay, after you press Enter you’ll see the phrase Hello World! on your
screen. That’s it! You’ve just run your first Python script!
If this doesn’t work right, maybe you’ll need to check your system PATH, your Python
installation, the way you created the hello.py script, the place where you saved it, and so on.
This is the most basic and practical way to run Python scripts.
1.String
Python has a built-in string class named "str" with many handy features (there is an older module
named "string" which you should not use). String literals can be enclosed by either double or
single quotes, although single quotes are more commonly used. Backslash escapes work the
usual way within both single and double quoted literals -- e.g. \n \' \". A double quoted string
literal can contain single quotes without any fuss (e.g. "I didn't do it") and likewise single quoted
string can contain double quotes. A string literal can span multiple lines, but there must be a
backslash \ at the end of each line to escape the newline. String literals inside triple quotes, """ or
''', can span multiple lines of text.
Python strings are "immutable" which means they cannot be changed after they are created (Java
strings also use this immutable style). Since strings can't be changed, we construct *new* strings
as we go to represent computed values. So for example the expression ('hello' + 'there') takes in
the 2 strings 'hello' and 'there' and builds a new string 'hellothere'.
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++,
Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'. If the index is out of bounds for the
string, Python raises an error. The Python style (unlike Perl) is to halt if it can't tell what to do,
rather than just make up a default value. The handy "slice" syntax (below) also works to extract
any substring from a string. The len(string) function returns the length of a string. The [ ] syntax
and the len() function actually work on any sequence type -- strings, lists, etc.. Python tries to
make its operations work consistently across different types. Python newbie gotcha: don't use
"len" as a variable name to avoid blocking out the len() function. The '+' operator can
concatenate two strings. Notice in the code below that variables are not pre-declared -- just
assign to them and go.
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there
Unlike Java, the '+' does not automatically convert numbers or other types to string form. The
str() function converts values to a string form so they can be combined with other strings.
pi = 3.14
##text = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes
For numbers, the standard operators, +, /, * work in the usual way. There is no ++ operator, but
+=, -=, etc. work. If you want integer division, it is most correct to use 2 slashes -- e.g. 6 // 5 is 1
(previous to python 3000, a single / does int division with ints anyway, but moving forward // is
the preferred way to indicate that you want int division.)
The "print" operator prints out one or more python items followed by a newline (leave a trailing
comma at the end of the items to inhibit the newline). A "raw" string literal is prefixed by an 'r'
and passes all the chars through without special treatment of backslashes, so r'x\nx' evaluates to
the length-4 string 'x\nx'. A 'u' prefix allows you to write a unicode string literal (Python has lots
of other unicode support features -- see the docs below).
raw = r'this\t\n and that'
2.String Methods
Here are some of the most common string methods. A method is like a function, but it runs "on"
an object. If the variable s is a string, then the code s.lower() runs the lower() method on that
string object and returns the result (this idea of a method running on an object is one of the basic
ideas that make up Object Oriented Programming, OOP). Here are some of the most common
string methods:
3.The % method
Python has a printf()-like facility to put together a string. The % operator takes a printf-type
format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a
tuple on the right (a tuple is made of values separated by commas, typically grouped inside
parentheses):
# % operator
text = "%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down." % (3, 'huff',
'puff', 'house')
The above line is kind of long -- suppose you want to break it into separate lines. You cannot just
split the line after the '%' as you might in other languages, since by default Python treats each
line as a separate statement (on the plus side, this is why we don't need to type semi-colons on
each line). To fix this, enclose the whole expression in an outer set of parenthesis -- then the
expression is allowed to span multiple lines. This code-across-lines technique works with the
various grouping constructs detailed below: ( ), [ ], { }.
# Add parentheses to make the long line work:
text = (
"%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down."
% (3, 'huff', 'puff', 'house'))
That's better, but the line is still a little long. Python lets you cut a line up into chunks, which it
will then automatically concatenate. So, to make this line even shorter, we can do this:
# Split the line into chunks, which are concatenated automatically by Python
text = (
"%d little pigs come out, "
"or I'll %s, and I'll %s, "
"and I'll blow your %s down."
% (3, 'huff', 'puff', 'house'))
The simplest way to produce output is using the print() function where you can pass zero or more
expressions separated by commas. This function converts the expressions you pass into a string
before writing to the screen.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Language Components
1.The if statement
[statement(s) to execute]
Relational operators are used to establish some sort of relationship between the two operands.
Some of the relevant examples could be less than, greater than or equal to operators. Python
language is capable of understanding these types of operators and accordingly return the output,
which can be either True or False.
The list of operators available includes:
1. Less than → used with <
2. Greater than → used with >
3. Equal to → used with ==
4. Not equal to → used with !=
5. Less than or equal to → used with <=
6. Greater than or equal to → used with >=
1. Logical AND: For AND operation the result is True if and only if both operands are True.
The keyword used for this operator is and.
2. Logical OR: For OR operation the result is True if either of the operands is True. The
keyword used for this operator is or.
3. Logical NOT: The result is True if the operand is False. The keyword used for this operator
is
4. The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
5. We generally use this loop when we don't know beforehand, the number of times to
iterate.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only
the test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.In Python, the body of the
while loop is determined through indentation.Body starts with indentation and the first
unindented line marks the end.Python interprets any non-zero value as True. None and 0 are
interpreted as False.
4.For Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Collection
1.List
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets.
Example
Create a List:
Example
Example
You can loop through the list items by using a for loop:
Example
Example
Apple
Banana
cherry
To determine how many items a list has, use the len() method:
Example
Output
To add an item to the end of the list, use the append() method:
Example
Example
output
C:\Users\My Name>python demo_list_insert.py
['apple', 'orange', 'banana', 'cherry']
Example
Output
Example
The pop() method removes the specified index, (or the last item if index is not specified):
Example
Output
Example
Example
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Example
2.Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.
Example
Create a Set:
You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using thein keyword.
Example
for x in thisset:
print(x)
Example
print("banana" in thisset)
2.2. Change Items
Once a set is created, you cannot change its items, but you can add new items.
To add more than one item to a set use the update() method.
Example
thisset.add("orange")
print(thisset)
Example
print(thisset)
To determine how many items a set has, use the len() method.
Example
print(len(thisset))
2.5. Remove Item
Example
thisset.remove("banana")
print(thisset)
Example
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
Example
x = thisset.pop()
print(x)
print(thisset)
Example
thisset.clear()
print(thisset)
Example
del thisset
print(thisset)
Example
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specifi
intersection_update() Removes the items in this set that are not present in other, specified se
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
3. Dictionaries
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
3.1. Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
You can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
Example
for x in thisdict:
print(x)
Example
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
3.5. Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example
print(len(thisdict))
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear
print(thisdict)
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's
an example of a simple module, support.py
return
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches before
importing a module. For example, to import the module support.py, you need to put the
following command at the top of the script −
#!/usr/bin/python
import support
support.print_func("Zara")
Hello : Zara
2. Standard module-Sys
The sys module provides information about constants, functions and methods of the Python
interpreter. dir(system) gives a summary of the available constants, functions and methods.
Another possibility is the help() function. Using help(sys) provides valuable detail information.
The module sys informs e.g. about the maximal recursion depth (sys.getrecursionlimit() ) and
provides the possibility to change (sys.setrecursionlimit())
The current version number of Python can be accessed as well:
>>> sys.version
>>> sys.version_info
(2, 6, 5, 'final', 0)
>>>
3.Standard module-math
The math module is a standard module in Python and is always available. To use mathematical
functions under this module, you have to import the module using import math.
Function Description
copysign(x,
Returns x with the sign of y
y)
Python has defined a module, “time” which allows us to handle various operations regarding
time, its conversions and representations, which find its use in various applications in life. The
beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is
termed as “epoch” in Python.
4.1.2. gmtime(sec) :- This function returns a structure with 9 values each representing a time
attribute in sequence. It converts seconds into time attributes(days, years, months etc.)till
specified seconds from epoch. If no seconds are mentioned, time is calculated till present. The
structure attribute table is given below.
4.1.3. asctime(“time”) :- This function takes a time attributed string produced by gmtime() and
returns a 24 character string denoting time.
4.1.4. ctime(sec) :- This function returns a 24 character time string but takes seconds as argument
and computes time till mentioned seconds. If no argument is passed, time is calculated till
present.
4.1.5. sleep(sec) :- This method is used to hault the program execution for the time specified in
the arguments.
Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt
is made to execute it. Errors detected during execution are called exceptions and are not
unconditionally fatal: you will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error messages as shown here:
It is possible to write programs that handle selected exceptions. Look at the following example,
which asks the user for input until a valid integer has been entered, but allows the user to
interrupt the program (using Control-Cor whatever the operating system supports); note that a
user-generated interruption is signalled by raising the KeyboardInterrupt exception.
>>>
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is
finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped.
Then if its type matches the exception named after the except keyword, the except clause
is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled
exception and execution stops with a message as shown above.
2. Raise
The raise statement allows the programmer to force a specified exception to occur. For example:
The sole argument to raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception). If an exception class is
passed, it will be implicitly instantiated by calling its constructor with no arguments:
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler
form of the raise statement allows you to re-raise the exception:
>>>
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
1. Introduction
Like all high-level languages, Python is easy to read, takes less time to write, and is portable.
This versatile programming language has two versions: Python 2 and Python 3. Wiki says:
Python 2.x is legacy, Python 3.x is the present and future of the language. That is, Python 2 is no
longer in development and all new features will be added in Python 3. Note that, keeping this in
mind, the code examples in this tutorial are in Python 3. Wherever Python 2.x code is shown, it
will be highlighted.
2. Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has to be read or written in the
file. There are 6 access modes in python.
2.1.Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of
the file. If the file does not exists, raises I/O error. This is also the default mode in which file
is opened.
2.2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned
at the beginning of the file. Raises I/O error if the file does not exists.
2.3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the file
does not exists.
2.4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
2.5.Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
2.6.Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it
does not exist. The handle is positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method
returns the number of characters written to the file.
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.
There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of the
file.
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get
empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).
56
>>> f.seek(0) # bring file cursor to initial position
0
>>> print(f.read()) # read the entire file
This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. This is both efficient and fast.
Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file. This method reads a
file till the newline, including the newline character.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
Classes in Python
1.Classes in Python
Focusing first on the data, each thing or object is an instance of some class.
The primitive data structures available in Python, like numbers, strings, and lists are designed to
represent simple things like the cost of something, the name of a poem, and your favorite colors,
respectively.
What if you wanted to represent something much more complicated? For example, let’s say you
wanted to track a number of different animals. If you used a list, the first element could be the
animal’s name while the second element could represent its age. How would you know which
element is supposed to be which? What if you had 100 different animals? Are you certain each
animal has both a name and an age, and so forth? What if you wanted to add other properties to
these animals? This lacks organization, and it’s the exact need for classes.
Classes are used to create new user-defined data structures that contain arbitrary information
about something. In the case of an animal, we could create an Animal() class to track properties
about the Animal like the name and age.
It’s important to note that a class just provides structure—it’s a blueprint for how something
should be defined, but it doesn’t actually provide any real content itself. The Animal() class may
specify that the name and age are necessary for defining an animal, but it will not actually state
what a specific animal’s name or age is.
It may help to think of a class as an idea for how something should be defined.
While the class is the blueprint, an instance is a copy of the class with actual values, literally an
object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog
named Roger who’s eight years old.
Put another way, a class is like a form or questionnaire. It defines the needed information. After
you fill out the form, your specific copy is an instance of the class; it contains actual information
relevant to you.
You can fill out multiple copies to create many different instances, but without the form as a
guide, you would be lost, not knowing what information is required. Thus, before you can create
individual instances of an object, we must first specify what is needed by defining a class.
class Dog:
pass
You start with the class keyword to indicate that you are creating a class, then you add the name
of the class (using CamelCase notation, starting with a capital letter.)
Also, we used the Python keyword pass here. This is very often used as a place holder where
code will eventually go. It allows us to run this code without throwing an error.
The (object) part in parentheses specifies the parent class that you are inheriting from (more on
this below.) In Python 3 this is no longer necessary because it is the implicit default.
3.1.Instance Attributes
All classes create objects, and all objects contain characteristics called attributes (referred to as
properties in the opening paragraph). Use the __init__() method to initialize (e.g., specify) an
object’s initial attributes by giving them their default value (or state). This method must have at
least one argument as well as the self variable, which refers to the object itself (e.g., Dog).
class Dog:
self.name = name
self.age = age
In the case of our Dog() class, each dog has a specific name and age, which is obviously
important to know for when you start actually creating different dogs. Remember: the class is
just for defining the Dog, not actually creating instances of individual dogs with specific names
and ages; we’ll get to that shortly.
Similarly, the self variable is also an instance of the class. Since instances of a class have varying
values we could state Dog.name = name rather than self.name = name. But since not all dogs
share the same name, we need to be able to assign different values to different instances. Hence
the need for the special self variable, which will help to keep track of individual instances of
each class.
4.Inheritance
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.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
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
4.1.Python Multi-Level inheritance
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 provides us the flexibility to inherit multiple base classes in the child class.
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 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.
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() 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.
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
Regular Expression
1.Introduction
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module
raises the exception re.error if an error occurs while compiling or using a regular expression.
We would cover two important functions, which would be used to handle regular expressions.
But a small thing first: There are various characters, which would have special meaning when
they are used in regular expression. To avoid any confusion while dealing with regular
expressions, we would use Raw Strings as r'expression'
2.Match Object
2.1class re.MatchObject
Match objects always have a boolean value of True.
Since match() and search() return None when there is no match, you can test whether
there was a match with a simple if statement:
2.2.expand(template)
Return the string obtained by doing backslash substitution on the template
string template, as done by the sub() method. Escapes such as \nare converted to the
appropriate characters, and numeric backreferences (\1, \2) and named backreferences
(\g<1>, \g<name>) are replaced by the contents of the corresponding group.
2.3.group([group1, ...])
Returns one or more subgroups of the match. If there is a single argument, the result is a
single string; if there are multiple arguments, the result is a tuple with one item per
argument. Without arguments, group1 defaults to zero (the whole match is returned). If
a groupN argument is zero, the corresponding return value is the entire matching string; if
it is in the inclusive range [1..99], it is the string matching the corresponding
parenthesized group. If a group number is negative or larger than the number of groups
defined in the pattern, an IndexError exception is raised. If a group is contained in a part
of the pattern that did not match, the corresponding result is None. If a group is contained
in a part of the pattern that matched multiple times, the last match is returned.
>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'
If a group matches multiple times, only the last match is accessible:
For example:
m.string[m.start(g):m.end(g)]
Note that m.start(group) will equal m.end(group) if group matched a null string. For
example, after m = re.search('b(c?)', 'cba'), m.start(0) is 1, m.end(0) is
2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an IndexError exception.
2.7.pos
The value of pos which was passed to the search() or match() method of
the RegexObject. This is the index into the string at which the RE engine started looking
for a match.
2.8.endpos
The value of endpos which was passed to the search() or match() method of
the RegexObject. This is the index into the string beyond which the RE engine will not
go.
2.9.lastindex
The integer index of the last matched capturing group, or None if no group was matched
at all. For example, the expressions (a)b, ((a)(b)), and((ab)) will have lastindex == 1 if
applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied
to the same string.
2.10.lastgroup
The name of the last matched capturing group, or None if the group didn’t have a name,
or if no group was matched at all.
3. Quantifiers
A quantifier has the form {m,n} where m and n are the minimum and maximum times the
expression to which the quantifier applies must match. For
example,both e{1,1}e{1,1} and e{2,2} match feel, but neither matches felt.
Writing a quantifier after every expression would soon become tedious, and is certainly difficult
to read. Fortunately, the regex language supports several convenient shorthands. If only one
number is given in the quantifier, it's taken to be both the minimum and the maximum, so e{2} is
the same as e{2,2}. As noted in the preceding section, if no quantifier is explicitly given, it's
assumed to be 1 (that is, {1,1} or {1}); therefore, ee is the same as e{1,1}e{1,1} and e{1}e{1}, so
both e{2} and ee match feelbut not felt.
Having a different minimum and maximum is often convenient. For example, to
match travelled and traveled (both legitimate spellings),we could use
either travel{1,2}ed or travell{0,1}ed. The {0,1} quantification is used so often that it has its
own shorthand form, ?, so another way of writing the regex (and the one most likely to be used
in practice) is travell?ed.
Two other quantification shorthands are provided: A plus sign (+) stands for {1,n} ("at least
one") and an asterisk (*) stands for {0,n} ("any number of"). In both cases, n is the maximum
possible number allowed for a quantifier, usually at least 32767. Table 2 shows all the
quantifiers.
The + quantifier is very useful. For example, to match integers, we could use \d+ to match one or
more digits. This regex could match in two places in the string 4588.91, for
example: 4588.91 and 4588.91. Sometimes typos are the result of pressing a key too long. We
could use the regex bevel+ed to match the legitimate beveled and bevelled, and the
incorrect bevellled. If we wanted to standardize on the single-l spelling, and match only
occurrences that had two or more l's, we could use bevell+ed to find them.
The * quantifier is less useful, simply because it can lead so often to unexpected results. For
example, supposing that we want to find lines that contain comments in Python files, we might
try searching for #*. But this regex will match any line whatsoever, including blank lines,
because the meaning is "match any number of pound signs"—and that includes none. As a rule
for those new to regexes, avoid using *at all, and if you do use it (or if you use ?), make sure that
at least one other expression in the regex has a nonzero quantifier. Use at least one quantifier
other than * or ?, that is, since both of these can match their expression zero times.
Often it's possible to convert * uses to + uses and vice versa. For example, we could match
"tasselled" with at least one l using tassell*ed or tassel+ed, and match those with two or more l's
using tasselll*ed or tassell+ed.
If we use the regex \d+ it will match 136. But why does it match all the digits, rather than just the
first one? By default, all quantifiers are greedy—they match as many characters as they can. We
can make any quantifier nongreedy (also called minimal) by following it with a question mark
(?) symbol. (The question mark has two different meanings—on its own it's a shorthand for
the {0,1} quantifier, and when it follows a quantifier it tells the quantifier to be nongreedy.) For
example, \d+? can match the string 136 in three different places: 136, 136, and 136. Here's
another example: \d?? matches zero or one digits, but prefers to match none since it's nongreedy;
on its own it suffers the same problem as * in that it will match nothing—that is, any text at all.
Table 2 Regular Expression Quantifiers
Syntax Meaning
4.Splitting Strings
re.split(regex, subject) returns an array of strings. The array contains the parts of subject
between all the regex matches in the subject. Adjacent regex matches will cause empty strings
to appear in the array. The regex matches themselves are not included in the array. If the regex
contains capturing groups, then the text matched by the capturing groups is included in the
array. The capturing groups are inserted between the substrings that appeared to the left and
right of the regex match. If you don't want the capturing groups in the array, convert them
into non-capturing groups. The re.split() function does not offer an option to suppress
capturing groups.
You can specify an optional third parameter to limit the number of times the subject string is
split. Note that this limit controls the number of splits, not the number of strings that will end
up in the array. The unsplit remainder of the subject is added as the final string to the array. If
there are no capturing groups, the array will contain limit+1 items.
The behavior of re.split() has changed between Python versions when the regular expression
can find zero-length matches. In Python 3.4 and prior, re.split() ignores zero-length matches.
In Python 3.5 and 3.6 re.split() throws a FutureWarning when it encounters a zero-length
match. This warning signals the change in Python 3.7. Now re.split() also splits on zero-length
matches.