Professional Documents
Culture Documents
Python Programming Digital Notes
Python Programming Digital Notes
on
PYTHON PROGRAMMING
I B. Tech II Semester
2020-2021
UNIT I
PYTHON Programming
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python provides many useful features which make it popular and valuable from
the other programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed
below a few essential features.
Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line
to execute, while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line
at a time. The advantage of being interpreted language, it makes debugging easy
and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte
code, and any platform can use that byte code.
It provides a vast range of libraries for the various fields such as machine learning,
web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django,
flask, pyramids are the popular framework for Python web development.
Graphical User Interface is used for the developing Desktop application. PyQT5,
Tkinter, Kivy are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs
code line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code.
We can use Python source code in another programming language as well. It can
embed other language into our code.
12. Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign
some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to
write int x = 15. Just write x = 15.
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any application.
Here, we are specifying application areas where Python can be applied.
1) Web Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction
to any application. Python provides a Tk GUI library to develop a user interface.
Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
PyQt or Pyside
3) Console-based Application
Python provides many free library or module which helps to build the command-line
apps. The necessary IO libraries are used to read and write. It helps to parse argument
and create console help text out-of-the-box. There are also advance libraries that can
develop independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support language
and can be used to build control and management, testing, etc.
Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
This is the era of Artificial intelligence where the machine can perform the task
the same as the human. Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6) Business Applications
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc. The few multimedia libraries are given below.
Gstreamer
Pyglet
QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by using
the following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can
be manipulated according to our requirements. Some libraries of image processing are
given below.
OpenCV
Pillow
SimpleITK
Many students get introduced to computer science only through Python language,
which is the same language used for in-depth research projects.
7) First-choice Language
Python language is the first choice for many programmers and students due to the
main reason for python being in high demand in the development market. Students and
developers always look forward to learning a language that is in high demand. Python is
undoubtedly the hottest cake in the market now.
Many programmers and data science students are using python language for their
development projects. Learning python is one of the important section in data science
certification courses. In this way, the python language can provide plenty of fantastic
career opportunities for students. Due to the variety of applications of python, one can
pursue different career options and will not remain stuck to one.
10) Automation
Python language can help a lot in automation of tasks as there are lots of tools and
modules available, which makes things much more comfortable. It is incredible to know
that one can reach an advanced level of automation easily by just using necessary python
codes.
Python is the best performance booster in the automation of software testing also.
One will be amazed at how much less time and few numbers of lines are required to write
codes for automation tools.
Java:
Python programs are generally expected to run slower than Java programs, but
they also take much less time to develop. Python programs are typically 3-5 times shorter
than equivalent Java programs. This difference can be attributed to Python's built-in high-
level data types and its dynamic typing. For example, a Python programmer wastes no
time declaring the types of arguments or variables, and Python's powerful polymorphic
list and dictionary types, for which rich syntactic support is built straight into the
language, find a use in almost every Python program. Because of the run-time typing,
Python's run time must work harder than Java's. For example, when evaluating the
expression a+b, it must first inspect the objects a and b to find out their type, which is not
known at compile time. It then invokes the appropriate addition operation, which may be
an overloaded user-defined method. Java, on the other hand, can perform an efficient
integer or floating point addition, but requires variable declarations for a and b, and does
not allow overloading of the + operator for instances of user-defined classes.
For these reasons, Python is much better suited as a "glue" language, while Java is
better characterized as a low-level implementation language. In fact, the two together
make an excellent combination. Components can be developed in Java and combined to
form applications in Python; Python can also be used to prototype components until their
design can be "hardened" in a Java implementation. To support this type of development,
a Python implementation written in Java is under development, which allows calling
Python code from Java and vice versa. In this implementation, Python source code is
translated to Java bytecode (with help from a run-time library to support Python's
dynamic semantics).
Javascript:
Perl :
Python and Perl come from a similar background (Unix scripting, which both
have long outgrown), and sport many similar features, but have a different philosophy.
Perl emphasizes support for common application-oriented tasks, e.g. by having built-in
regular expressions, file scanning and report generating features. Python emphasizes
support for common programming methodologies such as data structure design and
object-oriented programming, and encourages programmers to write readable (and thus
maintainable) code by providing an elegant but not overly cryptic notation. As a
consequence, Python comes close to Perl but rarely beats it in its original application
domain; however Python has an applicability well beyond Perl's niche.
Tcl:
Tcl 8.0 addresses the speed issuse by providing a bytecode compiler with limited
data type support, and adds namespaces. However, it is still a much more cumbersome
programming language.
Smalltalk:
Perhaps the biggest difference between Python and Smalltalk is Python's more
"mainstream" syntax, which gives it a leg up on programmer training. Like Smalltalk,
Python has dynamic typing and binding, and everything in Python is an object. However,
Python distinguishes built-in object types from user-defined classes, and currently doesn't
allow inheritance from built-in types. Smalltalk's standard library of collection data types
is more refined, while Python's library has more facilities for dealing with Internet and
WWW realities such as email, HTML and FTP.
Python has a different philosophy regarding the development environment and
distribution of code. Where Smalltalk traditionally has a monolithic "system image"
which comprises both the environment and the user's program, Python stores both
standard modules and user modules in individual files which can easily be rearranged or
distributed outside the system. One consequence is that there is more than one option for
attaching a Graphical User Interface (GUI) to a Python program, since the GUI is not
built into the system.
C++:
Almost everything said for Java also applies for C++, just more so: where Python
code is typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter
than equivalent C++ code! Anecdotal evidence suggests that one Python programmer can
finish in two months what two C++ programmers can't complete in a year. Python shines
as a glue language, used to combine components written in C++.
These languages are close to Python in their dynamic semantics, but so different in
their approach to syntax that a comparison becomes almost a religious argument: is Lisp's
lack of syntax an advantage or a disadvantage? It should be noted that Python has
introspective capabilities similar to those of Lisp, and Python programs can construct and
execute program fragments on the fly. Usually, real-world properties are decisive:
Common Lisp is big (in every sense), and the Scheme world is fragmented between many
incompatible versions, where Python has a single, free, compact implementation.
We can now write directly into the Python Interpreter and if used properly, it
should be able to run code one line at a time and in the order, we write them. For example,
let’s try the “Hello World” program.
Here we see the print () function. Anything inside the parentheses and between the
quotes will display in the Terminal. If we leave it blank, it won’t print anything.
Python provides us the feature to execute the Python statement one by one at
the interactive prompt. It is preferable in the case where we are concerned about the
output of each line of our Python program.
To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on your
system).
It will open the following prompt where we can execute the Python statement and
check their impact on the console.
Here, we get the message "Hello World !" printed on the console.
1.10.2 Scripting Mode Programming
Interpreter prompt is good to run the individual statements of the code. However, we
cannot write the code every-time on the terminal.
We need to write our code into a file which can be executed later. For this purpose, open
an editor like notepad, create a file named first.py (Python used .py extension) and write
the following code in it.
1. print ("hello world"); #here, we have used print() function to print the message on the c
onsole.
To run this file named as first.py, we need to run the following command on the terminal.
$ python3 first.py
1. CPython:
It is a Python compiler that was implemented in C language. Even C++ code can be
execute using CPython.
2. JPython:
3. IronPython:
It is compiler designed for .NET framework, but it is written in C#. It can run on
CLR(Common Language Run time).
4. PyPy:
It is a Python implemented by using Python language itself. It runs fast since JIT is
incorporated to PVM.
5. Ruby Python:
It acts as a bridge from Ruby to Python interpreter. It embeds the Python interpreter
inside the Ruby application.
6. Pythonxy:
7.Anaconda Python:
The name Anaconda Python is obtained after redeveloping it to handle large scale data
processing, predictive analytics and scientific computing. It handles huge amount of
data.
8. Stackless Python:
Tasklets are the small tasks that are run independently. The communication is
done with each by using channels. They schedule, control and suspend the tasklets.
Hundreds of tasklets can run by a thread. The thread and tasklets can be created in
stackless python. It is a re-implementation of python.
Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.
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.
Python Installation:
$ apt-get update
2) Install Python
$ python
For Python3 type the following command, then it will show the other version as
well.
$ python3
Well, on the basis of these commands, we can test application for both Python versions.
To set the path of python, we need to the right click on "my computer" and go to
Properties → Advanced → Environment Variables.
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 local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements.
JupyterLab
Jupyter Notebook
QtConsole
Spyder
Glue
Orange
RStudio
Visual Studio Code
Anaconda distribution comes with over 250 packages automatically installed, and
over 7,500 additional open-source packages can be installed from PyPI as well as
the conda package and virtual environment manager. It also includes a GUI, Anaconda
Navigator, as a graphical alternative to the command line interface (CLI).
The big difference between conda and the pip package manager is in how package
dependencies are managed, which is a significant challenge for Python data science and
the reason conda exists.
3. Click Next.
5. Select an install for “Just Me” unless you’re installing for all users (which requires
Windows Administrator privileges) and click Next.
6. Select a destination folder to install Anaconda and click the Next button.
Choose whether to add Anaconda to your PATH environment variable. We recommend
not adding Anaconda to the PATH environment variable, since this can interfere with
other software. Instead, use Anaconda software by opening Anaconda Navigator or the
Anaconda Prompt from the Start Menu.
Choose whether to register Anaconda as your default Python. Unless you plan on
installing and running multiple versions of Anaconda or multiple versions of Python,
accept the default and leave this box checked.
Click the Install button. If you want to watch the packages Anaconda is installing,
click Show Details
Click the Next button
Optional: To install PyCharm for Anaconda, click on the link
to https://www.anaconda.com/pycharm.
After a successful installation you will see the “Thanks for installing Anaconda”
dialog box:
1.17 JUPYTER Notebook:
2. Install the version of Anaconda which you downloaded, following the instructions on the
download page.
Important
Jupyter installation requires Python 3.3 or greater, or Python 2.7. IPython 1.x, which included the
parts that later became Jupyter, was the last version to support Python 3.2 and 2.6.
As an existing Python user, you may wish to install Jupyter using Python’s
package manager, pip, instead of Anaconda.
First, ensure that you have the latest pip; older versions may have trouble with
some dependencies:
1.18 SPYDER:
Once you install Spyder through this method, it will be added to your system as a
Python module. Therefore, it will not appear on your Control Panel. If you need to
uninstall Spyder, you'll have to use the following command:pip uninstall spyder
To run Spyder on Windows, you can either type the command "spyder3" in a
command prompt or search for spyder3 in the start menu.
1.19 Python IDE- JUPYTER Notebook Environment:
IDE stands for Integrated Development Environment. It’s a coding tool which
allows you to write, test, and debug your code in an easier way, as they typically offer
code completion or code insight by highlighting, resource management, debugging tools
and even though the IDE is a strictly defined concept, it’s starting to be redefined as other
tools such as notebooks start gaining more and more features that traditionally belong to
IDEs. For example, debugging your code is also possible in Jupyter Notebook.
Features of Spyder:
Some of the remarkable features of Spyder are:
Choose the version that is suitable for your OS and click on Download.
Once the installer is downloaded, you can see a dialog box for the Setup. Complete the
Setup and click on Finish.
Then, search for Anaconda Navigator in the search bar of your system and launch
Spyder. Once launched, you will see a screen similar to the one below:
Creating a file/ Starting a Project:
File–>New File
Projects–>New Project
In the above example, you can notice that the editor is showing the complete syntax of
the print function.
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
Class names should start with capital letters. For example, Person, Employee, etc.
If the class name has multiple words, use Uppercase for the first character of each word.
For example, EmployeeData StringUtils, etc.
You should use small letters for variables, functions, and module names. For
example, collections, foo (), etc.
If variables, functions, and module names have multiple words then separate them with
an underscore. For example, is empty (), employee_object, etc.
For private variables, you can start their names with an underscore.
Avoid underscore as the first and last character in the identifier name. It’s used by python
built-in types.
If the identifier starts and ends with two underscores, then it means that the identifier is a
language-defined special name. So, you should avoid having two underscores at the start
and the end of the identifier name.
Keep identifier names meaningful to clarify their intent. For
example, phone_number, is_uppercase, etc.
If a function returns boolean value, it’s better to start its name with “is”. For
example, isidentifier, iskeyword, etc.
There is no limit on the length of the identifier name. But, keep it small and to the point.
For example, the_employee_object_first_name can be better named
as emp_first_name.
Examples of identifiers:
Keywords are the reserved words in Python. We cannot use them as constant or
variable or any other identifier names. They are used to define the syntax and the structure of
the Python program. All the Python keywords contain lowercase letters only.
There are 33 keywords in Python 3. This number can vary slightly over the course of
time. All the keywords except True, False and None are in lowercase and they must be written
as they are. The list of all the keywords is given below.
The above keywords may get altered in different versions of Python. Some extra might
get added or some might be removed. You can always get the list of keywords in your current
version by typing the following in the prompt.
1.23 VARIABLES:
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
In Python, variables need not be declared or defined in advance, as is the case in many
other programming languages. To create a variable, you just assign it a value and then start
using it.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume , etc)
1.24 COMMENTS:
Comments are descriptions that help programmers better understand the intent and
functionality of the program. They are completely ignored by the Python interpreter.
Other than that, comments can also be used to ignore some code while testing other
blocks of code. This offers a simple way to prevent the execution of some lines or write a quick
pseudo-code for the program.
A hash sign (#) that is not inside a string literal begins a comment. All characters after
the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.
Single-Line Comments:
Example:
# printing a string
Print(“hello world”)
Multi-Line Comments:
Python doesn't offer a separate way to write multiline comments. However, there are
other ways to get around this issue.
Example-1:
# it is a
# multiline
#comment
Example-2:
‘‘‘
It is a
Multiline comment
’’’
Most of the programming languages like c, c++, and java use braces {} to define a block
of code. Python uses indentation
Code blocks are identified by the indentation rather than using symbols like curly
braces. Without extra symbols, programs are easier to read. Also, indentation clearly identifies
which block of code a statement belongs to. Of course, code block can consists of single
statement too.
Python doesn’t support braces to indicate block of codes for class and function,
definitions or flow control. Block of codes are denoted by line indentation. All the continuous
lines indented with same number of spaces would form a block. Python strictly follows
indentation rules to indicate the blocks.
Example:
if (5>3):
The most common use of single and double quotes is to represent strings by enclosing
a series of characters.
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string. As shown in the code below, we
create these two strings using single and double quotes, respectively.
The triple quotes are used to span the string across multiple lines. For example, all the
following are legal:
word = 'word'
If the string contains double quotes, we can use single quotes to represent the string
such that we don’t have to escape the double quotes. However, if there are both single and
double quotes in the string, it’s a syntactical error if you don’t escape the quotes that are the
same as the enclosing ones used by the entire string. So, a backslash is placed before single
quote so that there will be a continuation in the statements as shown in below example
It should be noted that when a string starts or ends with a single or double quote and we
want to use the triple quote for the string, we need to use the ones that differ from the starting
or ending one.
Another use case of the triple quotes is to represent a multi-line string. An example is
given below. You can use either triple single or double quotes in Assigning Values to Variables.
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable.
This is read or interpreted as “n is assigned the value 300.” Once this is done, n can be used in
a statement or expression, and its value will be substituted.
>>>
Just as a literal value can be displayed directly from the interpreter prompt in a REPL session
without the need for print().
Later, if you change the value of n and use it again, the new value will be substituted instead
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
Example:
Print counter
Print miles
Print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively.
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For
Example:
a = b = c = 300
Here, an integer object is created with the value 300, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables. For
Example:
a, b, c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume , etc)
The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.
1. Numbers
2. Sequence Type
3. Dictionary
4. Boolean
5. Set
2.1.1 Numbers:
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
For example;
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
2.1.2Sequence Type:
String:
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns
'Python Python'.
Output:
List:
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Tuple:
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Output:
Dictionary:
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
it
Boolean:
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Output:
it
Set:
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values.
Output:
Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be
changed if it is a mutable object.
To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.
Immutable Objects: These are of in-built types like int, float, bool, string, unicode, tuple.
In simple words, an immutable object can’t be changed after it is created.
Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change. Use of mutable objects is recommended when
there is a need to change the size or content of the object
It is important to understand that every object in Python has an ID (identity), and type and
a value. Once created, the ID of an object never changes. It is a unique identifier for it, and it is
used behind the scenes by Python to retrieve the object when we want to use it.
The type also never changes. The type tells what operations are supported by the object and
the possible values that can be assigned to it.
The value can either change or not. If it can, the object is said to be mutable, while when it
cannot, the object is said to be immutable.
Output is:
Byte Arrays:
Byte arrays represent the mutable version of bytes objects. They expose most of the
usual methods of mutable sequences as well as most of the methods of the bytes type. Items
are integers in the range [0, 256).
Sets
Python provides two set types, set and frozenset. They are unordered collections of immutable
objects.
Frozen Sets:
As discussed in the previous section, frozensets are similar to sets. However, frozenset objects are
quite limited in respect of their mutable counterpart since they cannot be changed. Nevertheless,
they still prove very effective for membership test, union, intersection, and difference operations,
and for performance reasons.
Tuples:
The last immutable sequence type we’re going to see is the tuple. A tuple is a sequence of
arbitrary Python objects. In a tuple, items are separated by commas. These, too, are immutable, as
shown in the following example:
2.3 FUNDAMENTAL DATA TYPES:
Data type is a collection of data or items. The basic fundamental data types are numeric data
type which consists of the following:
INT
FLOAT
COMPLEX
BOOLEAN
STRING.
These represent numbers in the range -2147483648 through 2147483647. (The range
may be larger on machines with a larger natural word size, but not smaller.) When the result of
an operation would fall outside this range, the result is normally returned as a long integer (in
some cases, the exception OverflowError is raised instead). For the purpose of shift and mask
operations, integers are assumed to have a binary, 2’s complement notation using 32 or more
bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to
different values).
Plain integers (also just called integers) are implemented using long in C, which gives
them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value
for the current platform; the minimum value is -sys.maxint - 1). Long integers have unlimited
precision.
Numbers are created by numeric literals or as the result of built-in functions and
operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain
integers unless the value they denote is too large to be represented as a plain integer, in which
case they yield a long integer. Integer literals with an ‘L’ or ‘l’ suffix yield long integers (‘L’ is
preferred because 1l looks too much like eleven!).
These represent machine-level double precision floating point numbers. You are at the
mercy of the underlying machine architecture (and C or Java implementation) for the accepted
range and handling of overflow. Python does not support single-precision floating point
numbers; the savings in processor and memory usage that are usually the reason for using these
is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.
Floating point numbers are usually implemented using double in C; information about the
precision and internal representation of floating point numbers for the machine on which your
program is running is available in sys.float_info.
In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
following built-in functions.
Eg: x = 10
y = bin(x)
print (y)
result2 = hex(342)
print(result)
print(result2)
The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python
which are listed below:
6. callable() : is something
1. x = 8
that can be called. This
2. print(callable(x))
built-in function checks
and returns true if the OUTPUT: False
object passed appears to
be callable, otherwise
false.
7. compile() : takes source
1. code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code as input and returns
2. code = compile(code_str, 'sum.py', 'exec')
a code object which can
3. print(type(code))
later be executed by
4. exec(code)
exec() function. 5. exec(x)
OUTPUT: <class 'code'>
sum = 15
27. chr() :used to get a string result = chr(102) # It returns string representation of a c
representing a character har
which points to a Unicode print(result)
code integer. For example, print("is it string type:", type(result) is str)
chr(97) returns the string OUTPUT: ValueError: chr() arg not in range(0x110000)
'a'.
28. complex() :used to a = complex(1) # Passing single parameter
convert numbers or string b = complex(1,2) # Passing both parameters
print(a)
into a complex number
print(b)
OUTPUT: (1.5+0j)
(1.5+2.2j)
38. Set(): is a built-in class, and this result = set() # empty set
function is a constructor of this result2 = set('12')
class. print(result)
print(result2)
OUTPUT: set()
{'1', '2'}
OUTPUT: [‘c’,’e’,’m’,’r’,’w’]
44. next() :is used to fetch next number = iter([256, 32, 82])
item from the collection. item = next(number)
print(item)
1. item = next(number)
2. print(item)
OUTPUT: 256
32
45. input() :is used to get an input val = input("Enter a value: ")
from the user. print("You entered:",val)
OUTPUT: Enter a value: 45
You entered: 45
46. int() :is used to get an integer
1. val = int(10)
value 2. val2 = int(10.52)
3. val3 = int('10')
4. print("integer values :",val, val2, val3)
OUTPUT: integer values: 10 10 10
OUTPUT: 10
11
7
OUTPUT: True
False
True
True
Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
2 long(x [,base] )
3 float(x)
4 complex(real [,imag])
5 str(x)
6 repr(x)
7 eval(str)
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
12 frozenset(s)
13 chr(x)
14 unichr(x)
15 ord(x)
16 hex(x)
17 oct(x)
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described as
follows.
Arithmetic operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in the
following table.
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.
2.8.4 Bitwise Operators:
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.
For example,
2.8.5 Logical Operators:
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.
2.8.6 Membership Operators:
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.
The identity operators are used to decide whether an element certain class or type
2.9 Slicing and Indexing:
What is Python Slice?
On our way up the learning curve for Python, we only need to deal with Python
iterables not so huge. But when building an application with it, not always do we need to
retrieve the entire iterable. In such cases, slicing is useful as it lets us choose what to see and
focus on. This aids readability and implements abstraction.
To slice a iterable, we use the slicing operator, that is [ ]. To separate the start, stop, and step
values, we use the colon ( : ).
Say you want to declare a list with the values 1,2,3,4,5, and only want to see values 2,3, and 4.
You can slice the list for that.
1. >>> list=[1,2,3,4,5]
2. >>> list[1:4]
[2, 3, 4]
slice() is a constructor that creates a Python Slice object to represent the set of indices that
range(start, stop, step) specifies. With this, we can slice a sequence like a string, a tuple, a list, a
range object, or a bytes object. These are all objects that support sequence protocols and
implement __getitem__() and __len__().
The slice() function returns a Python Slice Object.
1. slice(stop)
You’ll see that we have two syntaxes. When we provide only one parameter value, it takes it to
be the stop value. This means to start and step are set to None.
1. >>>slice(3)
slice(None, 3, None)
1. >>> l=[1,2,3,4,5]
2. >>> l[slice(3)]
[1, 2, 3]
Note that it displays values at the indices 0, 1, and 2. It stops at index 3.
We can also specify the interval. Slicing a string may give us a substring when the step size is 1.
You must learn about Python String
1. >>> s='helloworld'
2. >>> s[slice(1,6,2)]
‘elw’
1. >>> s='helloworld'
2. >>> s[slice(1,6)]
‘ellow’
But like we’ve seen with lists earlier, we can pass negative indices too. These are what it
traverses from the right.
To read the same value right to left, we do:
1. >>> s='helloworld'
2. >>> s[slice(-5,-10,-1)]
‘wolle’
Here’s how we traverse right to left:
Python String Slice
Now let’s take a look at performing Python Slicing on tuples. Check the following code:
Positive Indices-
1. >>> t=(1,2,3,4,5)
2. >>> t[slice(2,4)]
(3, 4)
Negative Indices-
1. >>> t[slice(-1,-5,-2)]
(5, 3)
We have often sliced lists using [ : ]. Let’s try that one more time.
Remember the previous Python Slicing example? Now take a look at this-
1. >>> t[-1:-5:-2]
(5, 3)
So we concur that slicing is a way to choose indices for elements to show. What slice() really
does is give us indices for those. We can use the slice() function as a subscript.
When indexing, what happens when we do not pass one or more of the values?
1. >>> t[:3]#From 0 to 2
(1, 2, 3)
(4, 5)
(1, 2, 3, 4, 5)
1. >>> t[::-1]#Reverse
(5, 4, 3, 2, 1)
(5, 3, 1)
(1, 3, 5)
1. >>> t[:5:-1]#Index 5 to end (already ahead of that), right to left; results in empty tuple
()
1. >>> t
(1, 2, 3, 4, 5)
(5, 2)
1. >>> l=[1,2,3,4,5]
2. >>> l[1:4]
[2, 3, 4]
1. >>> l[1:4]=[2,3,3.5,4]
2. >>> l
[1, 2, 3, 3.5, 4, 5]
The length of the slice on the right should be equal to that on the left.
2. >>> l
[2, 3, 3.5, 5]
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1
2. if num%2 == 0:
3. print("Number is even")
Output:
Number is even
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
5. print("a is largest");
7. print("b is largest");
9. print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
2. if age>=18:
4. else:
Output:
Enter your age? 90
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
Output:
Number is even
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
4. elif number==50:
6. elif number==100:
8. else:
Output:
Example 2
10. lse:
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the
same code for a finite number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the print statement 10 times, we can print inside a loop which
runs up to 10 iterations.
The for loop in Python is used to iterate the statements or a part of the program several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
2. statement(s)
1. str = "Python"
2. for i in str:
3. print(i)
Output:
n
Example- 2: Program to print the table of the given number .
1. list = [1,2,3,4,5,6,7,8,9,10]
2. n = 5
3. for i in list:
4. c = n*i
5. print(c)
Output:
10
15
20
25
30
35
40
45
50s
1. list = [10,30,23,43,65,12]
2. sum = 0
3. for i in list:
4. sum = sum+i
Output:
The sum is: 183
The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.
Syntax:
1. range(start,stop,step size)
1. for i in range(10):
Output:
0123456789
2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)
Output:
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
2. for i in range(2,n,2):
3. print(i)
Output:
10
12
14
16
18
We can also use the range() function with sequence of numbers. The len() function is combined
with range() function which iterate through a sequence using indexing. Consider the following
example.
1. list = ['Peter','Joseph','Ricky','Devansh']
2. for i in range(len(list)):
3. print("Hello",list[i])
Output:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax is given below.
Syntax
3. #block of statements
4. #Other statements
4. for i in range(0,rows+1):
6. for j in range(i):
7. print("*",end = '')
8. print()
Output:
**
***
****
*****
2. for i in range(0,rows+1):
3. for j in range(i):
4. print(i,end = '')
5. print()
Output:
22
333
4444
55555
Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must
notice that if the loop contains any of the break statement then the else statement will not be
executed.
Example 1
1. for i in range(0,5):
2. print(i)
3. else:
Output:
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.
Output:
The Python while loop allows a part of the code to be executed until the given condition returns
false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero value
and false is 0.
1. i=1
3. While(i<=10):
4. print(i)
5. i=i+1
Output:
7
8
10
1. i=1
2. number=0
3. b=9
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i))
7. i = i+1
Output:
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program to
run continuously in the loop without any disturbance.
Example 1
1. while (1):
Output:
Example 2
1. var = 1
2. while(var != 2):
Output:
Entered value is 10
Entered value is 10
Entered value is 10
Infinite time
Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop
is broken using break statement, then the else block will not be executed, and the statement
present after else block will be executed. The else statement is optional to use with the while
loop. Consider the following example.
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
Output:
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
3. a = 0
4. b = 1
5. count = 0
6.
13. else:
17. c=a+b
19. a=b
20. b=c
21.
22. count += 1
Output:
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. In other words, we can say that break is used
to abort the current execution of the program and the control goes to the next line after the
loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
The syntax of the break is given below.
1. #loop statements
2. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
item matched
found at 2 location
Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.
Syntax
1. #loop statements
2. continue
Flow Diagram
Consider the following examples.
Example 1
1. i = 0
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
10
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.
Example 2
1. str = "JavaTpoint"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)
Output:
The pass statement is a null operation since nothing happens when it is executed. It is used in
the cases where a statement is syntactically needed but we don't want to use any executable
statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program
file. Consider the following example.
Example
1. list = [1,2,3,4,5]
2. flag = 0
3. for i in list:
5. if i==3:
6. pass
8. flag = 1
9. if flag==1:
11. flag=0
Output:
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It
just makes the control to pass by without executing any code. If we want to bypass any code
pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that, comments
are entirely ignored by the Python interpreter, where the pass statement is not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.
5. pass
Example - 2:
1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
5. print(i)
Output:
1. 1
2. 2
3. 3
6. 5
1. # Empty Function
2. def function_name(args):
3. pass
4. #Empty Class
5. class Python:
6. pass
UNIT III –ADVANCED DATA TYPES IN PYTHON
3.1 List:
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and reliable
type is the list.
A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].
IIf we try to print the type of L1, L2, and L3 using type() function then it will come out to be
a list.
1. print(type(L1))
2. print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
3.2 Tuple:
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar
to lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can be
defined as follows.
1. T1 = (101, "Peter", 22)
2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
T4 = ()
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.
3.3 SET:
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.
3.4 Frozenset:
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.
3.5 Dictionary:
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key. It is the mutable data-structure. The dictionary is defined
into element Keys and values.
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.
3.6 Range:
Signature
Parameters
start (optional) : It is an integer number that specifies the starting position. The Default value
is 0.
step (optional) : It is an integer that specifies the increment of a number. The Default value is
1.
Return
1. # empty range
2. print(list(range(0)))
3.
4. # using the range(stop)
5. print(list(range(4)))
6.
7. # using the range(start, stop)
8. print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Explanation:
Note: In the above example, we've converted the range to a Python list and returned a
generator-like object that only prints the output on demand.
A range object returned by the range constructor can also be accessed by its index. It can
support both positive and negative indices.
The below example creates a list of number between the given numbers using range()
function.
1. start = 5
2. stop = 12
3. step = 4
4.
5. print(list(range(start, stop, step)))
Output:
[5, 9]
The python bytes() function in Python is used for returning a bytes object. It is an immutable
version of bytearray() function.
Signature
bytes(source)
bytes(encoding)
bytes(error)
Parameters
encoding is optional unless source is string type. It is used to convert the string to bytes using
str.encode() function
errors is also an optional parameter. It is used when the source is string type. Also, when
encoding fails due to some error.
Return
Output:
The python bytearray() function returns a bytearray object and can convert objects into
bytearray objects, or create an empty bytearray object of the specified size.
Signature
Parameters
Return
Output:
3.8 None:
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for the end of lists in
Python.
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None
The indexing is processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default the index value is 0 so its starts from the 0th element and go for index -
1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (rightmost) of the list has the
index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.
Let's have a look at the following example where we will use negative indexing to access the
elements of the list.
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Lists are the most versatile data structures in Python since they are mutable, and their values
can be updated by using the slice and assignment operator.
Python also provides append() and insert() methods, which can be used to add values to the
list.
Consider the following example to update the values inside the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to the second index
4. list[2] = 10
5. print(list)
6. # Adding multiple-element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.
A list can be iterated by using a for - in loop. A simple list containing four strings, which can
be iterated as follows.
Output:
John
David
James
Jonathan
Python provides append() function which is used to add an element to the list. However, the
append() function can only add value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user
and printing the list on the console.
Output:
Python provides the remove() function which is used to remove the element from the list.
Consider the following example to understand this concept.
Example -
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
Output:
Python provides the following built-in functions, which can be used with the lists.
Example: 1- Write the program to remove the duplicate element of the list.
1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Example:2- Write a program to find the sum of the element in the list.
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
Example: 3- Write the program to find the lists consist of at least one common element.
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)
Output:
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from
0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also allows us
to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Consider the following example:
1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.
SN Function Description
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be
changed.
2. Tuple can simulate a dictionary without keys. Consider the following nested structure,
which can be used as a dictionary.
SN List Tuple
1 The literal syntax of list is shown by The literal syntax of the tuple is shown by the
the []. ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality The tuple provides less functionality than the
than a tuple. list.
5 The list is used in the scenario in which The tuple is used in the cases where we need
we need to store the simple collections to store the read-only collections i.e., the
with no constraints where the value of value of the items cannot be changed. It can
the items can be changed. be used as the key inside the dictionary.
6 The lists are less memory efficient than The tuples are more memory efficient
a tuple. because of its immutability.
You can access individual items in a nested list using multiple indexes.
The indexes for the items in a nested list are illustrated as below:
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]
print(L[2][2])
# Prints ['eee', 'fff']
print(L[2][2][0])
# Prints eee
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by the
passed sequence.
Output:
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list,
dictionary, set) can't be a member of set. Consider the following example.
Output:
<class 'set'>
In the above code, we have created two sets, the set set1 have immutable elements and set2
have one mutable element as a list. While checking the type of set2, it raised an error, which
means set can contain only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to create
a dictionary as well. So Python provides the set() method used without an argument to create
an empty set.
Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements when we
printed it remove the duplicity from the set.
Set can be performed mathematical operation such as union, intersection, difference, and
symmetric difference. Python provides the facility to carry out these operations with
operators or methods
Python provides the add() method and update() method which can be used to add some
particular item to the set. The add() method is used to add a single element whereas the
update() method is used to add multiple elements to the set. Consider the following example.
Output:
To add more than one item in the set, Python provides the update() method. It accepts iterable
as an argument.
Output:
Python provides the discard() method and remove() method which can be used to remove the
items from the set. The difference between these function, using discard() function if the item
does not exist in the set then the set remain unchanged whereas remove() method will
through an error.
Output:
Python provides also the remove() method to remove the item from the set. Consider the
following example to remove the items using remove() method.
Output:
We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element will
be popped from set.
Consider the following example to remove the item from the set using pop() method.
Output:
In the above code, the last element of the Month set is March but the pop() method removed
the June and January because the set is unordered and the pop() method could not determine
the last element of the set.
Python provides the clear() method to remove all the items from the set.
Output:
Despite the fact that discard() and remove() method both perform the same task, There is one
main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the Python will
not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in the
set, the Python will raise an error.
Example-
Output:
Output:
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
The intersection of two sets can be performed by the and & operator or the intersection()
function. The intersection of the two sets is given as the set of the elements that common in
both sets.
Consider the following example.
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies
the original set by removing the unwanted items, on the other hand, the intersection() method
returns a new set.
Output:
{'castle'}
The difference of two sets can be calculated by using the subtraction (-) operator or
intersection() method. Suppose there are two sets A and B, and the difference is A-B that
denotes the resulting set will be obtained that element of A, which is not present in the set B.
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Output:
{3, 4, 5, 6, 8, 9, 10}
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using
which we can check whether a set is a subset, superset, or equivalent to other set. The
boolean true or false is returned depending upon the items present inside the sets.
Output:
True
False
False
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.
Output:
<class 'frozenset'>
The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define the
dictionary is given below.
Syntax:
In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
Output
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Python provides the built-in function dict() method which is also used to create dictionary.
The empty curly braces {} is used to create empty dictionary.
Output:
Empty Dictionary:
{}
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values.
It would give the same result as given by the indexing.
The dictionary is a mutable data type, and its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method is
also used to update an existing value.
Note: If the key-value already present in the dictionary, the value gets updated. Otherwise,
the new keys added in the dictionary.
Example - 1:
Output:
Empty Dictionary:
{}
Example - 2:
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)
Output:
Empty Dictionary:
{}
The items of the dictionary can be deleted by using the del keyword as given below.
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined
The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.
The pop() method accepts the key as an argument and remove the associated value. Consider
the following example.
1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)
Output:
Python also provides a built-in methods popitem() and clear() method for remove elements
from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas
the clear() method removes all elements to the whole dictionary.
Example 1
# for loop to print all the keys of a dictionary
2. for x in Employee:
3. print(x)
Output:
Name
Age
salary
Company
Example 2
2. for x in Employee:
3. print(Employee[x])
Output:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by using values() method.
2. for x in Employee.values():
3. print(x)
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by using items() method.
1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
2. for x in Employee.items():
3. print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than
one value for a single key, then the value which is last assigned is considered as the value of
the key.
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Nam
e":"John"}
2. for x,y in Employee.items():
3. print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as
the key, but we cannot use any mutable object like the list as the key in the dictionary.
Output:
The built-in python dictionary methods along with the description are given below.
SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it
returns false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string representation.
4 type(variable) It is used to print the type of the passed variable.
The built-in python dictionary methods along with the description are given below.
SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the
None, /) values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed
key.
5 dict.has_key(key) It returns true if the dictionary contains the
specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= It is used to set the key to the default value if the
"None") key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value
pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()
UNIT IV
A function is a set of statements that take inputs, do some specific computation and
produces output. The idea is to put some commonly or repeatedly done task together and
make a function, so that instead of writing the same code again and again for different
inputs, we can call the function. Python also provides built-in functions like print(), etc.
but we can also create your own functions. These functions are called user-defined
functions.
1. It helps to divide the large programs into small groups so that we can read the code, and
debug the program faster and better.
2. Python Functions stop us from writing the same logic various times. We can bind the
logic in one function and then call the same over and over.
3. Many persons can work on the same program by assigning different functions to each of
them.
4. It encourages us to call the same function with different inputs over multiple times.
Syntax of Function
def function_name(parameters):
"""docstring""“
statement(s)
A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
Example of a function
def greet(name):
Docstrings :
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can
remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines. This string
is available to us as the __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
a parameter
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Example:
>>> greet('Paul')
Ex:
def greet(name):
greet('Paul')
The return statement is used to exit a function and go back to the place from where it
was called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
For example:
>>> print(greet("May"))
None
Here, None is the returned value since greet() directly prints the name and
no return statement is used.
Example of return
def absolute_value(num):
number""“
if num >= 0:
return num
else:
return –num
print(absolute_value(2))
print(absolute_value(-4))
Output
4
A parameter is the variable listed inside the parentheses in the function definition.
In Python, you can define a function that takes variable number of parameters
Ex:
def greet(name, msg):
"""This function greets to the person with the provided
message"""
print("Hello", name + ', ' + msg)
greet("Monica", "Good morning!")
Output
Hello Monica, Good morning!
Here, the function greet() has two parameters. Since we have called this function with
two arguments, it runs smoothly and we do not get any error.
If we call it with a different number of parameters, the interpreter will show an error
message.
Below is a call to this function with one and no parameters along with their respective error
messages.
For example ,
mylist.append([1,2,3,4])
return
mylist = [10,20,30]
changeme(mylist)
Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −
Output:
For example,
return
mylist = [10,20,30];
changeme( mylist );
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result –
Output:
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that are sent to the function when it is called.
1. Default Arguments
2. Keyword Arguments
3. Arbitrary Arguments
1. Default Arguments:
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=).
Here is an example:
"""
This function greets to the person with the provided message. If the message is not
provided, it defaults to "Good morning!"
"""
print("Hello", name + ', ' + msg)
greet("Python")
greet(“python”, “programming”)
Output:
Hello Python, Good morning!
Hello Python, programming
In this function, the parameter name does not have a default value and is required
(mandatory) during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is
optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example,
if we had defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument
In the following Python program we are calling a function and passing two integer values and it
is returning back the sum.
# func
return x + y
print(result) # 30
Now, imagine we want to create a sum function that can take any number of arguments (like 2,
3, 4 ...).The problem with above sum function is that we can only pass two arguments.Python
allows us to create functions that can take multiple arguments. So, lets create multi-argument
functions.
Following is the syntax to create a function that can take variable length arguments.
def func(*args):
Where, func is the name of the function and *args holds variable length arguments.
In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.
Program:
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
Output:
<class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40)
So, we can see that the args variable is of type tuple and we are also able to print all the values
that were passed to the function as a tuple.
Accessing multiple arguments:
Since the multiple arguments passed to the function are tuple so we can access them using for
loop. In the following Python program we are printing out the individual argument.
Program:
def sum(*args):
print(arg)
print('sum(10, 20)')
sum(10, 20)
So, now that we are able to access the individual argument passed to the function let's go ahead
and modify the sum function that we are working on to return us the sum of the arguments.
Program:
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Output:
30
60
100
1. Global Variables:
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside of the function.
Example : Create a Global Variable
x = "global”
def foo():
print("x inside:", x) //inside
foo()
print("x outside:", x) //outside
In the above code, we created x as a global variable and defined a foo() to print the global variable
x. Finally, we call the foo() which will print the value of x.
What if you want to change the value of x inside a function?
x = "global"
def foo():
x=x*2
print(x)
foo()
Output:
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not defined
inside foo().
2. Local Variables:
A variable declared inside the function's body or in the local scope is known as a local
variable.
Example : Accessing local variable outside the scope
def foo():
y = "local"
foo()
print(y)
Output:
NameError: name 'y' is not defined
The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.
Example: Create a Local Variable
Normally, we declare a variable inside the function to create a local variable.
def foo():
y = "local"
print(y)
foo()
Output:
local
Let's take a look at the earlier problem where x was a global variable and we wanted to modify x
inside foo().
Global and local variables
Here, we will show how to use global variables and local variables in the same code.
Example : Using Global and Local variables in the same code
x = "global "
def foo():
global x
y = "local"
x=x*2
print(x)
print(y)
foo()
Output:
global global
local
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.After calling the
foo(), the value of x becomes global global because we used the x * 2 to print two times global.
After that, we print the value of local variable y i.e local.
Forward indexing
Positive indexing:
In indexing, for accessing the individual character we can use slice operator [ ], inside
that specify index number.
str[0]=‘H’
str[1]=‘E’
str[2]=‘L’
str[3]=‘L’
str[3]=‘O’
if we try to access a character out of index range then interpreter will raise an IndexError.
>>> str[5]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str[5]
IndexError: string index out of range
The index must be an integer if we try to access the data with non-integer indexes values
then interpreter raises an TypeError.
negative indexing:
Python allows negative indexing for its sequence. The index of -1 refers to the last item,
-2 refers to last 2nd item. This is called backward indexing.
str=‘hello’
H E L L O
-5 -4 -3 -2 -1
Backward indexing
>>> str[-1]
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
4.9.2 String splitting:
split()
split() method breaks up a string at the specified separator and returns a list of strings.
syntax of split() is:
str.split(separator)
separator (optional)- It is a delimiter. The string splits at the specified separator. If
the separator is not specified, any whitespace (space) string is a separator.
Ex:
text='hello python programming'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.split(', '))
grocery1 = 'Milk, Chicken: Bread:coffee'
# Splitting at ':'
print(grocery1.split(':'))
Output:
[‘hello', ‘python', ‘programming']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
4.10 String Operators:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied
on the python string are as below:
Assignment operator: “=.”
Concatenate operator: “+”
String repetition operator: “*”
String slicing operator: “[]”
String comparison operator: “==” & “!=”
Membership operator: “in” & “not in”
Escape sequence operator: “\”
String formatting operator: “%” & “{}”
String Operators in Python:
1. Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “. Python
string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’
‘’’]. var_name = “string” assigns “string” to variable var_name.
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
Output:
String H E L L O W O R L D
Positive index 0 1 2 3 4 5 6 7 8 9
string[a]: Returns a character from a positive index a of the string from the left side as
string[-a]: Returns a character from a negative index a of the string from the right side as
string[a:-b]: Returns characters from positive index a to the negative index b of the
string[a:]: Returns characters from positive index a to the end of the string.
string[:b] Returns characters from the start of the string to the positive index b.
string[-a:]: Returns characters from negative index a to the end of the string.
string[:-b]: Returns characters from the start of the string to the negative index b.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
These operators are mainly used along with if condition to compare two strings where the
decision is to be taken based on string comparison.
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Output:
“a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is
not in the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False
if “a” is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Output:
To insert a non-allowed character in the given input string, an escape character is used.
An escape character is a “\” or “backslash” operator followed by a non-allowed character.
An example of a non-allowed character in python string is inserting double quotes in the
string surrounded by double-quotes.
1. Example of non-allowed double quotes in python string:
Code:
Output:
Code:
print(string)
Output:
String formatting operator is used to format a string as per requirement. To insert another
type of variable along with string, the “%” operator is used along with python string. “%”
is prefixed to another character indicating the type of value we want to insert along with the
python string. Please refer to the below table for some of the commonly used different
string formatting specifiers:
Operator Description
%c Character
%s String
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
What is a file?
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned
off, we use files for future use of the data.
If you are working in a large software application where they process a large number of data,
then we cannot expect those data to be stored in a variable as the variables are volatile in
nature.
As files are non-volatile in nature, the data will be stored permanently in a secondary device
like Hard Disk
How Python Handle Files?
If you are working in a large software application where they process a large number of
data, then we cannot expect those data to be stored in a variable as the variables are
volatile in nature.
As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk.
Types Of File in Python
There are two types of files in Python. They are:
1. Binary file
2. Text file
1. Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal text editor
but we can’t read the content present inside the file. That’s because all the binary files will be
encoded in the binary format, which can be understood only by a computer or machine. For
handling such binary files we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise, you
need a pdf reader software to open .pdf binary files.
2. Text files in Python:
Text files don’t have any specific encoding and it can be opened in normal text editor itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Python File Handling Operations
Most importantly there are 4 types of operations that can be handled by Python on files:
1. Open
2. Read
3. Write
4. Close
Other operations include:
1. Rename
2. Delete
4.12 opening a File:
Python provides the open() function which accepts two arguments, file name and access
mode in which the file is accessed.
The function returns a file object which can be used to perform various operations like
reading, writing, etc.
File object:
File objects contain methods and attributes that can be used to collect information about
the file you opened. They can also be used to manipulate said file.
To get a file object we use Python’s built-in open function
Syntax:
file_object = open(“filename”, “mode”)
where file_object is the variable to add the file object.
File objects contain methods and attributes that can be used to collect information
about the file you opened. They can also be used to manipulate said file.
mode – tells the interpreter and developer which way the file will be used.
Access Modes for File Objects:
r: Opens the file in read-only mode. Starts reading from the beginning of the file and is
the default mode for the open() function.
w: Opens in write-only mode. The pointer is placed at the beginning of the file and this
will overwrite any existing file with the same name. It will create a new file if one with
the same name doesn't exist.
a: Opens a file for appending new information to it. The pointer is placed at the end of
the file. A new file is created if one with the same name doesn't exist.
r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
w+: Opens a file for writing and reading.
a+: Opens a file for both appending and reading.
rb: Opens the file as read-only in binary format and starts reading from the beginning
of the file. While binary format can be used for different purposes, it is usually used when
dealing with things like images, videos, etc.
wb: Opens a write-only file in binary mode.
ab+: Opens a file for both appending and reading in binary mode
Ex:
#Create a text file
>>> f=open(“fdp.txt","w")
>>> f
Output:
<_io.TextIOWrapper name='demo.txt' mode='w' encoding='cp1252'>
Or
>>> with open("fdp1.py","w") as f:
f.write("this is 1st program")
f.close()
#to know the current path
>>> import os
>>> os.path
Output:
<module'ntpath'fromC:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-
32\\lib\\ntpath.py'>
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>> print(a[0])
this is first line
#Displaying second line from file
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[1])
This is file concepts in python
For suppose, If we want last line then use a[-1]
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[-1])
previous function is write function
4.15. Looping through the File:
We can iterate through the file handle, no need to call readlines().on large files, you don't have
to read all the lines (that's what readlines() does) at once.
In a with-statement, use open(file, mode) with mode as "r" to open file for reading. Inside
the with-statement, use a for-loop to iterate through the lines. Then, call str.strip() to strip the
end-line break from each line.
SAMPLE.TXT
This is
an existing file.
-----------------------------------
with open("sample.txt", "r") as a_file:
for line in a_file:
stripped_line = line.strip()
print(stripped_line)
OUTPUT
This is
an existing file.
Python Rename():
Python provides us with an “os” module which has some in-built methods that would
help us in performing the file operations such as renaming and deleting the file.
In order to use this module, first of all, we need to import the “os” module in our program
and then call the related methods.
rename() method:
This rename() method accepts two arguments i.e. the current file name and the new
file name.
Syntax:
os.rename(current_file_name, new_file_name)
Ex:
>>> import os
>>> os.rename("fdp1.txt","fdp2.txt")
Python remove() method:
We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("fdp2.txt")
Return Value
This method returns the current position of the file read/write pointer within the file.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
>>> print(f.tell())
20
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of the
file would be taken as the reference position.
seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
>>> print(f.readline())
3. read() in Python
The read() method returns the specified number of bytes from the file.
Syntax:
file.read(size)
Where size is the number of bytes to be read from the file.
Ex:
>>> f=open("abc.txt","r")
>>> a=f.read()
>>> print(a)
4. readable() in Python
This returns True if the object is readable
Ex:
>>> f=open("abc.txt",”r")
>>> f.readable()
True
>>> f=open("abc.txt","w")
>>> f.readable()
False
>>> f=open("abc.txt","a")
>>> f.readable()
False
5. readline( ) in Python:
The readline() method returns first line from the file.
Syntax
file.readline(size)
Ex:
>>> f=open("abc.txt","r")
>>> a=f.readline()
>>>print(a)
welcome to python programming
You can also specified how many bytes from the line to return, by using the size parameter.
Return only the five first bytes from the first line:
>>>f= open("demofile.txt", "r")
>>>print(f.readline(5))
6. readlines() in Python:
readlines() method returns a list containing each line in the file as a list item.
Ex:
>>> f=open("demo.txt","r")
>>> a=f.readlines()
>>> print(a)
['hi...hello...python‘,’welcome to python world']
7. seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
>>> print(f.readline()) #output: ‘This is file concepts in python\n'
8. seekable() in Python:
This returns whether file allows us to change the file position
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seekable()
True
9. tell() in Python
tell() tells us the current position of the cursor.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
This is file concepts in python\n'
>>> print(f.tell())
20
10. truncate():
This method truncates the file's size. If the optional size argument is present, the file
is truncated to (at most) that size.
The size defaults to the current position
This method would not work in case file is opened in read-only mode.
Syntax:
fileObject.truncate( [ size ])
Example:
>>> f=open(“fdp.txt","w")
>>> #fdp.txt size is 139bytes
>>> f.truncate()
0 >>> #fdp.txt size is 0 bytes
13. writelines():
The method writelines() writes a sequence of strings to the file.
The sequence can be any iterable object producing strings, typically a list of strings.
There is no return value.
Syntax:
fileObject.writelines( sequence)
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write function"])
>>>f.close()
Note: open new.txt file in your path and see the text
14. detach( ):
This detaches the underlying binary buffer from TextIOBase and returns raw stream from buffer.
syntax:
f.detach()
Ex:
>>> f=open("ab.txt","r")
>>> f.detach()
<_io.BufferedReader name='ab.txt'>
>>> f.read()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
f.read()
ValueError: underlying buffer has been detached
Ex:
>>> f=open("new.txt","w")
>>> print("Name of the File:",f.name)
Name of the File: new.txt
>>> print("Mode of the File:",f.mode)
Mode of the File: w
>>> print("closed?:",f.closed)
closed?: False
>>> f.close()
>>> print("closed?:",f.closed)
closed?: True
>>> print("Encoding of the File:",f.encoding)
Encoding of the File: cp1252
Encoding in Files
File encoding represents converting characters into a specific format which only a machine
can understand.
Different machines have different encoding format as shown below.
Microsoft Windows OS uses ‘cp1252’ encoding format by default.
Linux or Unix OS uses ‘utf-8’ encoding format by default.
Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.
Errors:
Common Exceptions:
An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to
tackle with.
Python provides us with the way to handle the Exception so that the other part of the code
can be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
There are two types of exception:
1. System defined exceptions
2. User-defined exceptions
1. System defined exceptions:
A list of System defined exceptions that can be thrown from a normal python program is
given below.
6. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
4. SyntaxError: Python interpreter syntax error
>>> for
File "<string>", line 1
for
^
SyntaxError: invalid syntax
SyntaxError exceptions are the only ones that do not occur at run-time.
They indicate an improperly constructed piece of Python code which cannot execute
until corrected.
These errors are generated at compile-time, when the interpreter loads and attempts to
convert your script to Python bytecode
5. IndexError: request for an out-of-range index for sequence
>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
IndexError is raised when attempting to access an index that is outside the valid range
of a sequence.
6. KeyError: request for a non-existent dictionary key
>>> aDict = {'host': 'earth', 'port': 80}
>>> print aDict['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
Mapping types such as dictionaries depend on keys to access data values. Such values
are not retrieved if an incorrect/nonexistent key is requested.
7.IOError: input/output error
>>> f = open("blah")
Traceback (innermost last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'blah‘
Attempting to open a nonexistent disk file is one example of an operating system
input/output (I/O) error. Any type of I/O error raises an IOError exception
2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Output:
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘
With except statement:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/'b'
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>typeerror.py
enter a value3
enter b value 4
error occured
3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Output:
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
With except statement:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/d
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>nameerror.py
enter a value2
enter b value3
error occured
Syntax
try:
#block of code
else:
#block of code
Handling All Exceptions:
If you really want to handle all errors, you can still do that too, but use BaseException
- BaseException
|- KeyboardInterrupt
|- SystemExit
|- Exception
|- (all other current built-in exceptions)
Python exception hierarchy or standard exceptions:
Ex:
try:
except BaseException, e:
# handle all errors
or
try:
except Exception, e:
# handle real errors
4.24 else block:
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the try
block.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
C:\Users\ajee\Desktop\py>else.py
Enter a:4
Enter b:0
can't divide by zero
C:\Users\ajee\Desktop\py>else.py
Enter a:4
Enter b:2
a/b = 2
Hi I am else block
4.25 Finally block :
The finally block will be executed regardless if the try block raises an error or not.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except :
print("please enter non-zero for denimoniator")
else:
print("Hi I am else block")
finally:
print("Thank you")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:3
a/b = 1
Hi I am else block
Thank you
Output:
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:0
please enter non-zero for denimoniator
Thank you
Assert statement in python:
Python has built-in assert statement to use assertion condition in the program.
assert statement has a condition or expression which is supposed to be always true. If
the condition is false assert halts the program and gives an assertionError.
It is used for debugging
Syntax:
assert <condition>,<error message>
Here error message is optional
Ex:
x = "hello”
assert x == "hello“
print(x)
#if condition returns False, AssertionError is raised
assert x == "goodbye", "x should be 'hello‘“
o/p:
hello
Traceback (most recent call last):
File "main.py", line 17, in <module>
assert x == "goodbye", "x should be 'hello‘”
AssertionError: x should be 'hello'
Any Python file, whose name is the module’s name property without the .py extension, is a
module.
Python libraries play a vital role in developing machine learning, data science, data
visualization, image and data manipulation applications and more.
A library is a collection of pre-combined codes that can be used iteratively to reduce the
time required to code. They are particularly useful for accessing the pre-written frequently
used codes, instead of writing them from scratch every single time. Similar to the physical
libraries, these are a collection of reusable resources, which means every library has a root
source. This is the foundation behind the numerous open-source libraries available in
Python.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func
that contains a code to print some message on the console.
Examples
pranshu = ('James', 24, 'M')
print(pranshu)
Output:
('James', 24, 'M')
OrderedDict()
The Python OrderedDict() is similar to a dictionary object where keys maintain the order of
insertion. If we try to insert key again, the previous value will be overwritten for that key.
Example
import collections
d1=collections.OrderedDict()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13
Output:
A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-
in dict class. It provides all methods provided by dictionary but takes the first argument as
a default data type.
Example
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])
Output:
0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.
5. 5 Math Module:
Python math module is defined as the most famous mathematical functions, which includes
trigonometric functions, representation functions, logarithmic functions, etc. Furthermore,
it also defines two mathematical constants, i.e., Pie and Euler number, etc.
Pie (n): It is a well-known mathematical constant and defined as the ratio of circumstance
to the diameter of a circle. Its value is 3.141592653589793.
Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.
Example
import math
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
log(fabs(x), base) is : -6.698970004336019
<
math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.
Example
import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))
Output:
log10(x) is : 1.1139433523068367
math.exp()
This method returns a floating-point number after raising e to the given number.
Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)
Output:
Example
import math
number = math.factorial(7)
print("The factorial of number:",number)
Output:
The factorial of number: 5040
5.6 OS Module:
Python OS module provides the facility to establish the interaction between the user and the
operating system. It offers many useful OS functions that are used to perform OS-based
tasks and get related information about operating system.
The OS comes under Python's standard utility modules. This module offers a portable way
of using operating system dependent functionality.
The Python OS module lets us work with the files and directories.
os.name()
This function provides the name of the operating system module that it imports.
Example
import os
print(os.name)
Output:
nt
os.mkdir()
The os.mkdir() function is used to create new directory. Consider the following example.
import os
os.mkdir("d:\\newdir")
It will create the new directory to the path in the string argument of the function in the D
drive named folder newdir.
os.getcwd()
It returns the current working directory(CWD) of the file.
Example
import os
print(os.getcwd())
Output:
C:\Users\Python\Desktop\ModuleOS
os.chdir()
The os module provides the chdir() function to change the current working directory.
import os
os.chdir("d:\\")
Output:
d:\\
os.rmdir()
The rmdir() function removes the specified directory with an absolute or related path. First,
we have to change the current working directory and remove the folder.
Example
import os
# It will throw a Permission error; that's why we have to change the current working
directory.
os.rmdir("d:\\newdir")
os.chdir("..")
os.rmdir("newdir")
There are different types of functions used in a random module which is given below:
random.random()
This function generates a random float number between 0.0 and 1.0.
random.randint()
This function returns a random integer between the specified integers.
random.choice()
This function returns a randomly selected element from a non-empty sequence.
Example
# importing "random" module.
import random
# We are using the choice() function to generate a random number from
# the given list of numbers.
print ("The random number from list is : ",end="")
print (random.choice([50, 41, 84, 40, 31]))
Output:
The random number from list is : 84
random.shuffle()
This function randomly reorders the elements in the list.
random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its argument. It
accepts three arguments, beginning number, last number, and step, which is used to skip a
number in the range. Consider the following example.
Output:
A random number from range is : 290
random.seed()
This function is used to apply on the particular random number with the seed argument. It
returns the mapper value. Consider the following example.
mean() function
The mean() function is used to calculate the arithmetic mean of the numbers in the list.
Example
import statistics
# list of positive integer numbers
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
# Printing the mean
print("Mean is :", x)
Output:
Mean is : 4.857142857142857
median() function
The median() function is used to return the middle value of the numeric data in the list.
Example
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("Median of data-set is : % s "
% (statistics.median(datasets)))
Output:
Median of data-set is : 4.5
mode() function
The mode() function returns the most common data that occurs in the list.
5.9 Sys Module:
The python sys module provides functions and variables which are used to manipulate
different parts of the Python Runtime Environment. It lets us access system-specific
parameters and functions.
import sys
First, we have to import the sys module in our program before running any functions.
sys.modules
This function provides the name of the existing python modules which have been imported.
sys.argv
This function returns a list of command line arguments passed to a Python script. The name
of the script is always the item at index 0, and the rest of the arguments are stored at
subsequent indices.
sys.base_exec_prefix
This function provides an efficient way to the same value as exec_prefix. If not running a
virtual environment, the value will remain the same.
sys.base_prefix
It is set up during Python startup, before site.py is run, to the same value as prefix.
In Python, the date is not a data type, but we can work with the date objects by importing
the module named with datetime, time, and calendar.
We can import multiple modules with a single import statement, but a module is loaded
once regardless of the number of times, it has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:
Enter the name?John
Hi John
calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while
accessing summation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from...import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn't let our code to be heavier. We can also import all the
attributes from a module by using *.
Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
5.15 Regular Expressions:
The regular expressions can be defined as the sequence of characters which are used to
search for a pattern in a string. The module re provides the support to use regex in the python
program. The re module throws an exception if there is some error while using the regular
expression.
Regex Functions
The following regex functions are used in the python.
It provides a getopt module, in which command line arguments and options can be parsed.
An object-oriented paradigm is to design the program using classes and objects. The object
is related to real-word entities such as book, house, pencil, etc. The oops concept focuses
on writing the reusable code. It is a widespread technique to solve the problem by creating
objects.
5.19 Object:
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1 object
will allocate memory for these values.
5.20 Class:
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain
an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
5.21 Method:
The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.
5.22 Inheritance:
Inheritance is the most important aspect of object-oriented programming, which simulates
the real-world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
5.23 Polymorphism:
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs
and cats) have a concrete implementation of the action "speak".
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
5.25 Encapsulation:
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects
of this class.
On the other hand, the object is the instance of a class. The process of creating an object can
be called instantiation.
Syntax
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of the
Employee.
Example
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables.
We can use anything instead of self, but it must be the first parameter of any function which
belongs to the class.
The following example creates the instance of the class Employee defined in the above
example.
Example
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two attributes named id
and name and assigned value to them. We can observe we have passed the self as parameter
in display function. It is used to refer to the same class attribute.
We have created a new instance object named emp. By using it, we can access the attributes
of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Output:
This is parametrized constructor
Hello John
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
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
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
class BaseN:
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:
Barking
Real Life Example of method overriding
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
emp.display()
Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look this option in this chapter.
JPython − JPython is a Python port for Java which gives Python scripts seamless access to
Java class libraries on the local machine http://www.jython.org
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
Enter the main event loop to take action against each event triggered by the user.
Example
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()