0% found this document useful (0 votes)
83 views18 pages

Introduction To Python

Python is a programming language that combines features of both C and Java. It offers both procedural and object-oriented capabilities. Python code is easy to read and understand due to its simple syntax that resembles English. It is an interpreted, high-level, general-purpose programming language that is open source, portable, and platform independent.

Uploaded by

singhjagjit23447
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
83 views18 pages

Introduction To Python

Python is a programming language that combines features of both C and Java. It offers both procedural and object-oriented capabilities. Python code is easy to read and understand due to its simple syntax that resembles English. It is an interpreted, high-level, general-purpose programming language that is open source, portable, and platform independent.

Uploaded by

singhjagjit23447
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

their

printfC"Sum= %d", (a+b)); /* display

is almost same as that of Java.


There is
course, preceding
the program
is that if the programmers
O code. Another problem o for
improvement in the length
of the
orientation which
is lacking in . Object orientat rientation
C language, they will miss the object
want to deal
with heavy projects.
becomes a n advantage when they
Nowadays, programmers want C style coding as well as the Java style object orientaswant
processing, they w
tation.
calculations or
functional aspects like objects, thev
when they want to develop need of going for classes
and
they will
when they a r e in
to use C style coding and is Python!
for their requirement
coding. The only
answer
use Java style

Python combines the ieatures or a n d Java. It ofe


ffers
language that want to go for obier
Python 1s a programming programmers
like C. When the
elegant style of developing
programs
like Java. In Python,
the program to ad
offers classes and objects
orientation. Python
be follows:
two numbers will
as

add two numbers 10 in to them


#Python program to
take two variables and store
a = b 10 # #display their sum
print("Sum= ", (a+b))
Hence, Python is
and develop. Hence,
is gaining
code is easy to understand
The preceding several other features of
the programming folks. Of course, there a r e
popularity among choice of most
which we will discuss in
future which make it the preferred
Python
programmers.
in the 1991
to a bit of developed by Guido Van Rossum
history, Python was
year
Coming the Dutch
the Center for Mathematics and Computer Science managed by
at
on a project to develop system
utilities in C where
Government. Van Rossum was working
with the Bourne shell available in UNIX. He
felt the necessity of
he had to interact
led the
the gap between C and the shell. This has
to
developing a language that would fill
creation of Python.
TV show, Monty
Van Rossum picked the name Python for the new language from the
was ready by early 1990
and van
Python's Flying Circus. Python's first working version
shows two
released it for the public on February 20, 1991. The logo of Python
Rossum
intertwined snakes as shown in Figure 1.1:

python
Figure I.I: Python Official Logo
Introduction to Python 3
Python is open source software, which means anybody can freely download it from
www.python.org and use it to develop programs. Its source code can be accessed and
modified as required in the projects.

Features of Python
There are various reasons why Python is gaining good popularity in the programming
community. The following are some of the important features of Python:

Simple: Python is a simple programming language. When we read a Python program,


we feel like reading English sentences. It means more clarity and less stress on
understanding the syntax of the language. Hence, developing and understanding
programs will become easy.

Easy to learn: Python uses very few keywords. Its programs use very simple
structure. So, developing programs in Python become easy. Also, Python resembles C
language. Most of the language constructs in C are also available in Python. Hence,
migrating from C to Python is easy for programmers.
Open source: There is no need to pay for Python software. Python can be freely
downloaded from www.python.org website. Its source code can be read, modified and
can be used in programs as desired by the programmers.

low level and high


of two types:
High level language: Programming languages are

level. A low level language uses machine code instructions to develop programs.
These instructions directly interact with the CPU. Machine language and assembly
language are called low level languages.

High level languages use English words to develop programs. These


easy to learn are

and use. Like COBOL, PHP or Java, Python also uses English words in its programs
and hence it is called high level programming language.
need not declare anything. An assignment
Dynamically typed: In Python, we
statement binds a name to an object, and the object can be of any type. lf a name is

may later be assigned object of different


assigned to an object of one type, it to an a

type. This is the meaning of the saying that Python is a dynamically typed language.

Languages like C and Java are statically typed. In these languages, the variable
names and datatypes should be mentioned properly. Attempting to assign an object
of the wrong type to a variable name triggers error or exception.

a Platform independent: When a Python program is compiled using a Python


compiler, it generates byte code. Python's byte code represents a fixed set of
instructions that run on all operating systems and hardware. Using a Python Virtual
Machine (PVM), anybody can run these byte code instructions on any computer
system. Hence, Python programs are not dependent on any specific operating system.
We can use Python on almost all operating systems like UNIX, Linux, Windows,
4 Chapter 1

Macintosh, Solaris, Os/2, Amiga, AROS, AS/400, etc. This makes Python
on an.
an ideal
programming language for any network or Internet.
Portable: When a program yields the same result on any computer in the world. .
it is called a portable
program. Python programs will give the same result since
then
are platform independent. Once a Python program is written, it can run on
computer system using PVM. However, Python also contains some system depen any
modules (or code). which are specific to operating system. Programmers shouli ndent
be
careful about such code while developing the software if they want it to be complea
portable
tel
Procedure and object oriented: Python is a procedure oriented as well as an obier
oriented programming language. In procedure oriented proOgramming languages (e
C and Pascal), the programs are built using functions and procedures. But in obiec
oriented languages (e.g. C++ and Java), the programs use classes and objects.

Let's get some idea on objects and classes. An object is anything that exists physically in
the real world. Almost everything comes in this definition. Let's take a dog with the nane
Snoopy. We can say Snoopy is an object since it physically exists in our house. Objects
will have behavior represented by their attributes (or properties) and actions. For
example, Snoopy has attributes like height, weight, age and color. These attributes are
represented by variables in programming. Similarly, Snoopy can perform actions like
king. biting eating. running, etc. These actions are represented by methods
(functions) in programming. Hence, an object contains variables and methods.
A class, on the other hand, does not exist physically. A class is only an abstract idea
which represents common behavior of several objects. For example, dog is a class. When
we talk about dog, we will have a
picture in our mind where we imagine head, body.
a
legs, tail, etc. This imaginary picture is called a class. When we take Snoopy, she has all
the features that we have in our mind but she exists
physically and hence she becomes
the object of dog class. Similarly all the other dogs like Tommy, Charlie, Sophie, etc
exhibit same behavior like Snoopy. Hence, they are all objects of the same class, i.e. dog
class. We should understand the point that the object Snoopy exists physically but tn
class dog does not exist physically. It is
only a picture in our mind with some attriDute
and actions at abstract level. When we take
have these attributes and actions and hence
Snoopy, Tommy, Charlie and Sophie, tu
they are all objectsof the dogclass.
As we described in the
preceding paragraph, a class indicates common behavo of
objects. This common behavior is represented by attributes and actions. Attribute
are

represented by variables and actions are performed by methods (functions). S0, a class

also contains variables and


methods just like an object does. Figure 1.2
shows

relationship between a class and its object:


Introduction to Python|

dog hasattributes: Snoopyhas ottributes


height
weight height
welght veriebles
age
color
color

doghosactions; Snoopy has octlons;


barking
biting barking
methods
eating bitins
or functions
running ting
running

cless dog
object Snoopy

Figure I.2: A Class and its object


Similarly. parrot, sparrow, pigeon and crow are objects of the bird class. We should
inderstand that bird (class) is only an idea that defines some attributes and actions. A
parrot and sparrow have the same attributes and actions but they exist physically.
Hence, they are objects of the bird class.

Object oriented languages like Python,.Java and .NET use the concepts of classes and
objects in their programs. Since class does not exist physically, there will not be any
memory allocated when the class is created. But, object exists physicaly and hence, a
separate block of memory is allocated when an object is created. In Python language
everything like variables, lists, functions, arrays etc. are treated as objects.

DInterpreted: A program code is called source code. After writing a Python program,
we should compile the source code using Python compiler. Python compiler
translates the Python program into an intermediate code called byte code. This byte
code is then executed by PVM. Inside the PVM, an interpreter converts the byte code
instructions into machine code so that the processor will understand and run that
machine code to produce results.

Extensible: The programs or pieces of code written in C or C++ can be integrated into
Python and executed using PVM. This is what we see in standard Python that is
downloaded from wwwpython.org. There are other flavors of Python where programs
from other languages can be integrated into Python. For example, Jython is useful to
integrate Java code into Python programs and run on JVM (Java Virtual Machine).
Similarly, Iron Python is useful to integrate .NET programs and libraries into Python
programs and run on CLR (Common Language Runtime).
Embeddable: We can insert Python programs into a C or C++ program. Several
applications are already developed in Python which can be integrated into other
programming languages like C, C+*, Delphi, PHP, Java and .NET. It means
programmers can use these applications for their advantage in various software

projects.
Huge library: Python has a big library which can be used on any operating system
ke UNIX, Windows or Macintosh. Programmers can develop programs very easily
using the modules available in the Python library.
S c r i p t i n g language: A scripting language is a programming language that does not
use a compiler for executing the source code. Rather, it uses an interpreter to
translate the source code into machine code on the fly (while running). Generally
application or software. Fr
Scripting languages perform supporting tasks for bigger
a
task of taking inpur
example, PHP is a scripting language that performs supporting
from an HTML page and send it to Web server software. Python is considered as a
the Internet to support other
scripting language as it is interpreted and it is used on

software.
Database connectivity: A database represents software that stores and manipulates
data. For example, Oracle is a popular database using which we can store data in the
form of tables and manipulate the data. Python provides interfaces to connect its
programs to all major databases like Oracle, Sybase or MySql.

Scalable: A program would be scalable if it could be moved to another operating


system or hardware and take full advantage of the new environment in terms of
performance. Python programs are scalable since they can run on any platform and
use the features of the new platform effectively.

Batteries included: The huge library of Python contains several small applications
(or small packages) which are already developed and immediately available to
programmers. These small packages can be used and maintained easily. Thus the
programmers need not download separate packages or applications in many cases
This will give them a head start in many projects. These libraries are called batteries
included'. Some interesting batteries or packages are given here:

argparse is a package that represents command-line parsing library


botois Amazon web services
library
CherryPy is anobject-oriented HTTP framework
cryptography offers cryptographic techniques for the programmers
Fiona reads and writes
big data files
jellyfish is a library for doing approximate and phonetic matching of strings
mysql-connector-pythonis
database
a driver written in
Python to connect to sQ
M
numpy 1s a
package for
processing arrays of single or
multidimensional type
Introduction to Python

pandas is a package for powerful data structures for data analysis, time series
and statistics

matplotlib is a package for drawing electroniccircuits and 2D graphs.


Pillou is a Python imaging library

pUquery represents jquery like library for Python


scpy is the scientific library to do scientific and engincering calculations

Sphinx is the Python documentation generator


sympy is a package for Computer algebra system (CAS) in Python

w3lib is a
library of web related functions
whoosh contains fast and pure
Python full text indexing, search and spell
checking library
To know the entire list of packages included in Python, one can Visit
https://www.pythonanywhere.com/batteries_included/
Execution of a Python Program
Let's assume that we write a Python program with the name
x.py. Here, x is the program
name and the -py is the extension name. Every Python program is typed with an
extension name .py. After typing the program, the next
step is to compile the program
using Python compiler. The compiler converts the Python program into another code
called byte code.

Byte code represents a fixed set of instructions that represents all operations like
arithmetic operations, comparison operations, memory related operations, etc., which
run on any operating system and hardware. It the
byte instructions are system
means
independent or platform independent. The size of each byte code instruction is 1 byte and
hence they are called with the name byte code. These byte code instructions are
contained in the file x.pyc. Here, the x.pyc file represents a python compiled file.

The next step is to run the program. If we directly give the byte code to the computer, it
cannot execute them. Any computer can execute only binary code which comprises ls
and Os. Since the binary code is understandable to the machine (computer), it is also
called machine code. It is therefore necessary to convert the byte code into machine code
so that our computer can understand and execute it. For this purpose, we should use
PVM (Python Virtual Machine.
PVM uses an interpreter which understands the byte code and converts it into machine
code. PVM first understands the processor and operating system in our computer. Then
it converts the byte code into machine code understandable to that processor and into
that format understandable to that operating system. These machine code instructions
are then executed by the processor and results are displayed.
8 Chapter1
An interpreter translates the program source code line by line. Hence, t To
1s rectify
Siow. The
this

interpreter that is found inside the PVM uns the Python program S also
compiler is added to the
PVM.
This compiler
probiem, in s o m e flavors of Python, a
interpreter. is This compiler
than the
code machine code but faster speed
Converts the byte into
JIT compiler
is to improve of
advantage of
called J T (Just In Time) compiler. The
the pertrmance
e N e c u t i o n of a Python program and
thus inproving
in all Python
environnents.
For
not available using c
We should remember that JIT compiler is which is created

is called CPython
software c r e a t e d in Python
the s t a n d a r d Python which is
pie. But, PyPy,
JIT compiler. in the PVM. So,
the PyP
does not include a
anguage that addition to a n interpreter
t h a n CPython
compiler in
anguage itself u s e s a JIT e x e c u t i o n of the
Python p r o g r a m s
offers faster
Tiavor of Python definitely
a Python
program:
1.3 shows the steps for executing
Figure
101011010100101

Python compiled file 101010110101001

010101101010011
Python Program x.pyc run using8
PY compiile Python Virtual
using Python Machine
machine code
compiler computer
byte code
sOurce code

Execution of a Python Program


Figurel.3: Steps of
cannot s e e the Pyc file produced bv
.

Python program, w e
Normally, when we compile
a
by the PVM. This is done internally
and the machine code generated
the Python compiler Python program namne
visible. For example, if
our

in the memory
and the output is finally
to compile it a s :
is x.py, we c a n u s e Python compiler
C:Ppython x.py
is the command for calling Python compiler. The
the
In the preceding statement, python
x.py the file into its byte code equivalent file, x.pyc. Instead of
compiler should convert result.
the output or
doing this, the compiler directly displays
The
files in the directory with the extension .pyc.
If we observe, we cannot find any
the sequence: source code >byte code machine code
r e a s o n is that all the steps in Hence, after
output are completed and then the final result is displayed.
internally
execution, we cannot find any .pyc file in the directory.
create .pyc file from the source code, we can u s e the following command:
To separately
C:>python -m py_compile x.py
-1"
In the preceding command, the Python compiler with -m option.
we are calling
represents module and the module name is pPy_compile. This module generates the P
"ent
file for the specified Py file. The compiler creates a separate directory in the cur
D
directory by the name. Pycache where it stores the .pyc file. The .pyc file name may
he
something like: x.cpython-34.pyc. The word cpython here indicates that we are using
Python compiler that was created using C. This is of course, the standard Pytn
compiler.
Introduction to Python
9
So the question is What is the use of the pycfiles? We know that the .pyc files contain
byte code. We get these files after the compilation is completed. Hence, the first step is
over. The next step is to interpret them using PVM. This can be done by calling the
Python compiler as
C:>python x.cpython-34.pyc
In this case, we aresupplying pye file to the Python compiler. Now, Python compiler will1
skip the first step where it has to convert the source code into byte code as already it sees
the byte code inside this .pyc file. This file is executed
directly by the PVM to produce the
output. Hence, the program takes less time to run and the performance will be
This is the reason that after the
improved.
completion of the project, the .pyc files are distributed to
the user who can directly run these files PVM
using and view the
output
Viewing the Byte Code
Let's consider the following Python program:
#
a
Python
=b
program to add two numbers
10 take two variables and store 10 in to them
printC"Sum=", (a+b)) # display their sum
We can type this program in a text editor like
Notepad and then save it as
first.py'. It
means, the first.py file contains the source code.
Now, let's compile the program using Python
compiler as:

C:python first.py
It will display the result as:
Sum= 20
That is ok. But we do not want the
output of the program. We want to see the
instructions that were created byte code
internally by the Python compiler before they are executed
by the PVM. For this purpose, we should
command as:
specify the dis module while using python

C:python -m dis first.py


It will produce the following output:
2 0 LOAD_CONST 0 (10)
3 DUP TOP
4 STORE_NAME
7 STORE_NAME
3 10 LOAD_NAME 12 (b
(print)
13 LOAD_CONST
16 LOAD_NAME 1 ('Sum=')
19 LOAD_NAME 0 (a)
22 BINARY ADD 1 (b)
23 CALL_FUNCTION
2 (2
26 POPTOP positional, 0 keyword pair)
27 LOAD_CONST 2 (None)
30 RETURN_VALUE
Python Virtual Machine (PVM)
We know that computers understand onlymachine code that comprises 1s and 0s. Since
computer understands only machine code, it is imperative that we should convert any
program into machine code before it is submitted to the computer for execution. For this
purpose, we should take the help of a compiler. A compiler normally converts the
program source code into machine code.

A Python compiler does the task but in a slightly different manner. It converts the
same

program source code into another code, called byte code. Each Python program
statement is converted into a group of byte code instructions. Then what is
byte code?
Byte code represents the fixed set of instructions created by Python developers
representing all types of operations. The size of each byte code instruction is 1 byte (or 8
12 Chapter 1

organization says that


bits) and hence these are called byte code instructions. Python
code instructions from time to
instructions added to the existing byte
there may be newer
1.4 snows the role of
file. Figure
time. We c a n find byte code instructions in the .pyc
into machine code
Virtual machine in converting byte code instructions

machine code
byte code

Interpreter
J
Python Virtual Machine
(PVM)

I.4: The Python Virtual Machine


Figure
is to convert the byte code instructions into
The role of Python Virtual Machine (PVM)
can execute those machine code
instructions and
machine code so that the computer
To carry out this conversion, PVM is equipped with
an
display the final output.
converts the byte code into machine code and sends that
interpreter. The interpreter
the
machine code to the computer processor for execution. Since interpreter is playing
main role, often the Python Virtual Machine is also called an interpreter.
Comparisons between C and Python
In Table 1.1. we will comparc of the
some
innportant fcatures of C and Python languages:
Table 1.1: Differences between C and Python
C
Python
C is procedure-oriented programming| Python is object-oriented oriented
language. it does not contain the features It contains features like classes,language.
like classes, objects,
objects, inheritance, inheritance, polymorphism, etc.
polymorphism, etc.
C programs execute faster.
Python programs are slower compared to C.
PyPy flavor or Python programs run a bit
faster but still slower than C.
It is compulsory to declare the
datatypes of Type declaration is not required in Python.
variables, arrays etc. in C.

Clanguage type discipline is static and | Python type discipline is dynamic and
weak.
strong.
Pointers concept is available in C. Python does not use pointers.
C does not have exception handling facility Python handles exceptions and hence Python
and hence C programs are weak. progranms are robust.

C has do... while, while and for loops. Python has while and for loops.

Chas switch statement. Python does not have switch statement.

The variable in for loop does not increment | The variable in the for loop increments
automatically. automatically.
C Python
The programmer shouid allocate and Memory allocation and deallo
location is
deallocate memory using malloc(). calloc(). automatically by PVM. done
realloc) or free() functions.

C does not contain a garbage collector. Automatic garbage collector is available


in
Python.
Csupports single and multi-dimensional Python supports only single dimension.
To work with multi-dimensional
arravs arrays.
arrays, we should use third
party
applications like numpy.

The array index should be positive integer. Array index can be positive or
negative
integer number. Negative index represents
locations from the end of the array.

Checking the location outside the allocation Python performs checking outside an array
of an arTay is not supported in C. for all iterations while looping.

Indentation of statements is not necessary Indentation is required to represent a block


inC. of statements.
A semicolon is used to terminate the | New line indicates end of the statements and
statements in C and comma is used to| semicolon is used as an expression
separate expressions. separator.

C supports in-line assignments. Python does not support in-line


assignments.

Comparisons between Java and Python


In Table 1.2, will compare of the
we some important features of Java and Python
languages:
Table 1.2: Differences between Java and Python
Java
Python
Java is object-oriented programming| Python blends the functional
language. Functional programming features with
programming
are introduced into Java 8.0
object-oriented programming
features.
lambda expressions. through Lambdas are already available in Python.
Java programs verbose. It
are
contain more number of lines.
means they Python programs are concise and compact. A
big program can be written using very leSs
number of lines.
It is compulsory to declare the datatypes of Type declaration is not required
variables, arrays etc. in Java. in Python.
Java language type discipline is static and
weak. Python type discipline is dynamic and
strong
Introduction to Python 17

Java Python
Java has do... while, while, for and for each Python has while and for loops.
loops
Java has switch statement. Python docs not have switch statement.
The variable in for loop does not increment The variable in the for loop increments
automatically. But in for each loop, it will automatically.
increment automatically.

Memory allocation and deal location is done Memory allocation and deal location is done
automatically by JVM (Java Virtual automatically by PVM (Python Virtual
Machine). Machine).
Java supports,single and multi-dimensional Python supports only single dimensional
arrays. arrays. To work with multi-dimensional
arrays, we should use third party
applications like numpy.
The array index should be a positive integer. | Array index can be positive or negative
integer number. Negative index represents
locations from the end of the array.

Checking the location outside the allocation Python performs checking outside an array
ofan array is not supported in Java. for all iterations while looping.
Indentation of statements is not necessary Indentation is required to represent a block
in Java. of statements.

A semicolon is used to terminate the New line indicates end of the statements and
statements and comma is used to separate semicolon i s used as an expression
expressions. separator.
In Java, the collection objects like Stack, Python collection objects like lists and
LinkedList or Vector store only objects but dictionaries can store objects of any type,
not primitive datatypes like integer including numbers and lists.
numbers.

Points to Remember
Python was developed by Guido Van Rossum in the year 1991.

Python is a high level programming language that contains features of functional


programming language like C and object oriented programming language like Java.

In object oriented terminology, an object represents a physical entity that contains


behavior. The behavior of an object is represented by attributes (or properties) and
actions. The attributes are represented by variables and actions are performed by
functions or methods.

In object oriented terminology, a class is an abstract idea which represents common


behavior of several objects. Class represents behavior and does not exist physically
Installing numpy ona
multi-dimensional arrays, we
Toreate
Fython supports only single dimensional arravs
10 aowoad
and
called Numerical Python packagc or numpy.
Ieed a specialpackage
and then
use PP ynon
install this package, first we should go to Svstem prompt

Installation of Packages) command as shown


below
C:> pip instal1 numpy
command is given, it
software bv default. When this
pip program c o m e s with Python downloads it and
searches the latest version of the numpy
package o n the Internet,

installs as shown in Figure 2.15:


it,
Command Prompt

C:1pip install numpy

Collecting numpy amd64.whi (13.1MB)


numpy-1.13.3-cp36-none-win
Downloading
13.1MB
13.1MB 104kB/s
100%
Installing collected packages
numpy
Successfully installed numpy
1.13.3

C:V
of numpy package
Figure 2.15: Installation
Internet while using this
this
Of course, our computer would have connected to the
command.
29
Writing our first Python program

Installing pandas
pandas is a package used in datn analysis, This package is mostly used by data
scientists and data analysts. To download and install this package, we should go to
System prompt and then use 'pip' (Python Installation of Packages) command as shown
below:
C: pip install pandas
This command downloads pandas package from the Intcrnct and installs it, as shown in
Figure 2. 16:

Commamd Prompt

cpip install pandas


collecting pandas
Downloading pandas-0.21.1-cp36-cp36m-win amd64, whl (9.1MB)
9.1MB 133kB/s
Collecting Python-dateutils=2 (from pandas)
DOwnloading python dateutil-2,6.1-py2.py3-none-any.whl (194kB)
194kB 1.3MB/S
collecting pytz=2011k (from pandas)
Downloading
100% |
pytz-20127.3-Py2 py3-none-any whl (511kB)
512kB 595kB/s
Requirement already satisfied: numpys=1:9.0 in c:\users\nageshwara raolappdata\locms \python\py
thon361b\site-packages (from pandas)
collecting six>=1.5 (from python-dateutil=2-3pandas)
Downloading six-1.11.0-py2.py3-none-any whl
Installing collected packages: six, python-dateutil, pytz, pandas
Successfully installed pandas-0.21.1 python-dateutil-2.6.1 Pytz-2017.3 six-1.11.
c
Figure 2.16: Installation of pandas package

Installing xlrd
xird is a package that is useful to retrieve data from Microsoft Excel spreadsheet files.
Hence, it is useful in data analysis. To download and install this package, we should go
to System prompt and then use pip' (Python Installation of Packages) command as
shown below:

C: pip install xlrd


This command downloads xlrd package from the Internet and installs it, as shown in
Figure 2.17:
AConénd Piomp

C:pip install xlrd


Collecting xlrd
Downloadingxlrd-1,1.0-py2,Py3-none any.whl (108kB)
100% 112kB 468kB/s
Installing collected packages: xlrd
Successfully installed xlrd-1.1.0

Figure 2.17: Installation of xlrd package


30 Chapter 2

Installing matplotlib thul usef irs


1o p r l u c p o o d
L1alit
another impoIlt pae kpee in Pylon i U e 10TIm ol gyaph.
atplotlib in
ol slowing alin and install.
UNedlor tlhe puupot elc, T0 (downoal hi
4DETAphea, It is motly parts,
designing
cireuitn,
chinery
clectroir
y t h o n Installai
n d then
ue Pip lation
SO
1O promp
Paekie,
we should go to SyaleI
command a s showIn below
P'ackapes)
install matplot1ib Jnternet and installsi
C: pip puuekap:
fron the

downlonds the matplotlib


conmand
This
2.18:
shown in Figure

Cond venpl

C:opip install matplotlib


collecting matplot1ib whi (B.7MB)
m a t p l o t l i b - 2 , 1 , 1 - c p 3 6 - c p 3 6 m - w i n _ a m d 6 4 .

Downloading 8.7MB 152kB/s


100% I c:\usors\nageshwara rao\appdata\python\py
numpy1,7.1 in
Requirement already satisfied:
thon36|1ib\site-packagos (from matplot1ib)
cycler>0. 10 (from matplot1ib)
Collecting
Downloading cyclor-0.10.0-py2.py3-nono-any.whl1
rao\appdata\lython\pytho
sixo=1.10 in c:\users\nageshwara
Requirement alroady satisfiod:
n3611ib\site-packages (from matplot1ib)
already satisfiod: python-dateutil>=2,0 in c:\users\nageshwara raáprogramslp
Requirement (from matplot1ib)
ython \python36\1ib\site-packagos
satisfied: pytz \usors\nagoshwara in c:
rao\appdata\local\jPython36
Requirement already
ib\site-packagos (from matplot1ib)
)=2.0.1 (from matplot1ib)
pyparsángl=2.0.4, I=2.1.2, I=2.1.6,
Collecting wh1 (56kB)
Downloading pyparsing-2.2,0-py2.py3-nono-any,
100% 61kB 2.OMB/s
matplotlib
Installing collectod package9: cycler, Pyparsing, pyparsing-2.2.0
Successfully installed cyclor-0,10.0 matplotlib-2.1.1

C:
Figure 2.18: Installation of matplotlib package

Verifying Installed Packages


We can verifly
whether the installed packages are added to our Python software
proper
or not by going into Python and typing the following command at Python prompt (tripe
greater than symbol) as:
» help( modules')D
For this purpose, first click the Python IDLE Window pinned at the taskbar and then yP
the preceding command as shown in Figure 2.19:
Writing our first Python program 31

hen A S
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MsC v.1900 64 on win32
TYpe "copyright", *credits" or "1i cense()" for more informat ioon.
>>help modules

Figure 2.19: To view the modules available in Python


It will display all the module names cunently available in your Python software as shown
in Figure 2.20:

LUUeU steLUmire
decima l collectíons marshal sre constantS
dummy_thread colorizer Ss] se
Sreparse
elementtree Colorsys matplot lib)
findvs compileall etypes stackviewer
stat
functools concurrent mmap
hashlib config modulef inder statistics
heapq config key msilib statusbar
-1mp configdialog msvcrt stringg
-10 contigparser multica11 stringprep
-Son Contextlib multiprocessing structt
-Ocale copy netrc. subprocess
Sprof copyre9 nntplibb sunau
1zma crypt nt symbo
Symtable
|markupbase CSV ntpath
mds ctypes ntur12path Sys
Dumbers sysconfig
msi CursesS
multibytecodec Cycler numpy tabnanny
tarfile
multiprocessing datet1me opcoue telnetlib
opcode dateutil operator
dbm optparse tempfile
-0perator OS test
OSXSupport debuggeer textview
-overlapped debugger
-pickle debugob pandas textwrap
-Pyclbr debugobjr paragraph this
pydecima1 decima parenmatch threadi ng
-Py1o delegator parser time
random difflib pathbrOwser timeit

Figure 2.20: To verify installed packages in Pychon

You can verify that your Python software now has the packages like: numpy, xlrd,
and matplotlib available as modules.
pandas,

Writing Our First Python Program


We want to write our first Python program and execute it. This will also help us to test
whether our installation is correct or not. Let's write our first program to add two
numbers. First have a look at the Python program code given here:

# first program to add two numbers 1ine 1


10 # store 10 into variable a ine 2
15 #store 15 intovari able b - line 3
= a + b # add 10 and 15 and, store into vari able c -

line 4
print("Sum= ", C) # display the sum 1 i n e 5
The hash symbol '#" represents the comment line in Python. A comment is useful too

describe the elements of a program. Comments are not executed by the Python compiler
or PVM. Hence, it is not compulsory to write comments; however, commnents improve
understanding of a program. We started the above program with a comment
line tha
gives the aim of our program.
We all know that the data and results are
always stored in compu
These memory locations are called variables'. In the second ne of our locations,
Stored the d a t a 10 into a
line or
variable ( o rmemory location) by the n a n e
our
l' as:
program, we e

a 10
variable ' b as:
arIy, in the third line, we stored data 15 into another

b 15
+ b. The result of this sum should
n the fourth line, we added them by writing a e
name 'c' as:
stored into another memory location by the
C= a +b
result the screen for the user. This is
So, the result is in c'. We should now display the on

function is to perform a task. The printa


of a
done by the print() function. The purpose
and w e can use it for display purpose as:
function is already written by Python developers
print(c)
the result 25. But, we want to display some message while displaving
This will display
the result as:

Sum= 25
This will help the user to understand the results clearly. For this purpose, we used the

print() function in fifth line as:

print"sum= ", c)
Here, "Sum= "is called a string. A string contains a group of characters and is usually
enclosed in double quotes or single quotes. Strings are displayed without any change, as
they are. After this string, we put a comma and then wrote 'c'. This will display the result
as:

Sum= 25

Executing a Python Program


There are three ways of executing a Python program.

Using Python's command line window


Using Python's IDLE graphics window
Directly from System prompt
The first two are called interactive modes where we can type the program one line at a
time and the PVM executes it immediately. The last one is called non-interactive mode
where we ask the PVM to execute our program after typing the entire program.

You might also like