Introduction To Python
Introduction To Python
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:
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.
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.
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
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.
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
cless dog
object Snoopy
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.
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:
pandas is a package for powerful data structures for data analysis, time series
and statistics
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
010101101010011
Python Program x.pyc run using8
PY compiile Python Virtual
using Python Machine
machine code
compiler computer
byte code
sOurce code
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
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
machine code
byte code
Interpreter
J
Python Virtual Machine
(PVM)
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.
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.
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.
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.
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
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:
Cond venpl
C:
Figure 2.18: Installation of matplotlib package
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
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
You can verify that your Python software now has the packages like: numpy, xlrd,
and matplotlib available as modules.
pandas,
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
Sum= 25
This will help the user to understand the results clearly. For this purpose, we used the
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