Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

BCA – Sem 5 Python Programming CC-302

Unit 1 - Python Programming


What is Python?
Python is a high-level, object-oriented, interpreted, dynamically typed, case sensitive, versatile,
expressive, General purpose computer programming language created by Guido van Rossum
while working at National Research Institute at Netherlands and first released in 1991.
Python was picked the name Python for the new language from the TV show Monty Python's
Flying Circus which was broadcasted in BBC from 1969 to 1974.
Python is recommended as first programming language for beginners.
Python is a programming language that combines the features of C and Java. It offers elegant
style of developing programs like C. When the programmers want to go for object orientation,
Python offers classes and objects like Java.
The most common important application areas are:

1. For developing Desktop Applications


2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. Testing
6. For developing games
7. For Data Analysis Applications
8. For Machine Learning
9. For developing Artificial Intelligence Applications
10. For IoT

The biggest strength of Python is large library which can be used for the
following:

1. Machine Learning
2. GUI Applications
3. Web frameworks like Django (used by YouTube)
4. Multimedia
5. Image processing
6. Test frameworks
7. Web scraping
8. Scientific computing
9. Text processing
Companies Which Use Python

1. Internally Google and Youtube use Python coding


2. Netflix is developed by using Python
3. NASA and New York Stock Exchange Applications developed by Python
4. Top Software companies like Google, Microsoft, IBM, Yahoo using Python
Advantages of Python Compare to Other Languages

1. Simple
2. Easy to Learn
3. Open Source
4. High Level Language
5. Dynamically Typed

1|Page
BCA – Sem 5 Python Programming CC-302

6. Platform Independent
7. Portable
8. Procedure and Object Oriented
9. Interpreted
10. Extensible (Ex:- Jython for java integration, Iron Python for .Net)
11. Huge Library
12. Database Connectivity
Python Execution Process
Step 1:
Every Python program is typed , file name will be saved with an extension .py.
Step 2:
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.
Step 3:
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 1s and 0s. 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.

Python Bytecode
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 means the byte instructions are system
independent or platform independent. The size of each byte code instruction is 1 byte and hence
they are called with the name byte code.
Bytecode Explanation
Lets consider below program for viewing its byte code:

#Python Program to add two numbers.


a=b=10
# take two variable and store 10 in to them
Print(“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
2|Page
BCA – Sem 5 Python Programming CC-302

C:\>python first.py
It will display the result as: sum=20

Bytecode 'dis' module


We do not want the output of the program. We want to see the byte code instructions that were
created internally by the Python compiler before they are executed by the PVM.
For this purpose, we should specify the 'dis' module while using python command as:
C:\>python -m dis first.py
It will produce the following output:

1 0 LOAD_CONST 0 (10)
2 DUP_TOP
4 STORE_NAME 0 (a)
6 STORE_NAME 1 (b)

2 8 LOAD_NAME 2 (print)
10 LOAD_CONST 1 ('Sum =')
12 LOAD_NAME 0 (a)
14 LOAD_NAME 1 (b)
16 BINARY_ADD
18 CALL_FUNCTION 2
20 POP_TOP
22 LOAD_CONST 2 (None)
24 RETURN_VALUE

Flavors of Python
Flavors of Python refer to the different types of Python compilers. These flavors are useful to
integrate various programming languages into Python. The following are some of them:
CPython:
This is the standard Python compiler implemented in C language. This is the Python software
being downloaded and used by programmers directly from CPython . In this, any Python
program is internally converted into byte code using C language functions. This byte code is
run on the interpreter available in Python Virtual Machine (PVM) created in C language. The
advantage is that it is possible to execute C and C++ functions and programs in CPython.
Jython:
This is earlier known as JPython. This is the implementation of Python programming language
which is designed to run on Java platform. Jython compiler first compiles the Python program
into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to produce the
output. Jython contains libraries which are useful for both Python and Java programmers. This
can be downloaded from Jython .
IronPython:
This is another implementation of Python language for .NET framework. This is written in C#
(C Sharp) language. The Python program when compiled gives an intermediate language (IL)
which runs on Common Language Runtime (CLR) to produce the output. This flavor of Python
gives flexibility of using both the .NET and Python libraries. IronPython can be downloaded
from IronPython .
PyPy:
This is Python implementation using Python language. Actually, PyPy is written in a language
called RPython which was created in Python language. RPython is suitable for creating
language interpreters. PyPy programs run very fast since there is a JIT (Just In Time) compiler
added to the PVM. PyPy can be downloaded by visiting the page: PyPy . Since the original
Python uses only an interpreter in the Python Virtual Machine (PVM), the Python programs

3|Page
BCA – Sem 5 Python Programming CC-302

run slowly. To improve the speed of execution, a compiler called JIT (Just In Time) is
introduced into the PVM of PyPy. Hence, PyPy programs run faster than those of Python. We
can download PyPy from PyPy .
RubyPython:
This is a bridge between the Ruby and Python interpreters. It encloses a Python interpreter
inside Ruby applications. This flavor of Python can be downloaded from RubyPython .
StacklessPython:
Small tasks which should run individually are called tasklets. Tasklets run independently on
CPU and can communicate with others via channels. A channel is a manager that takes care of
scheduling the tasklets, controlling them and suspending them. A thread is a process which
runs hundreds of such tasklets. We can create threads and tasklets in StacklessPython which is
reimplementation of original Python language. This can be downloaded
from StacklessPython .
Pythonxy:
This is pronounced as Python xy and written as Python(X,Y). This is the Python
implementation that we get after adding scientific and engineering related packages. We can
download Pythonxy from Pythonxy .
AnacondaPython:
When Python is redeveloped for handling large-scale data processing, predictive analytics and
scientific computing, it is called Anaconda Python. This implementation mainly focuses on
large scale of data. This can be downloaded from AnacondaPython .

Python Virtual Machine (PVM)


We know that computers understand only machine 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 same task but in a slightly different manner. It converts the
program source code into another code, called byte code. Each Python program statement is
converted into a group of byte code instructions. 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 8bits) and hence these are called byte code instructions.
Python organization says that there may be newer instructions added to the existing byte code
instructions from time to time. We can find byte code instructions in the .pyc file.
Following Figure shows the role of virtual machine in converting byte code instructions into
machine code:

The role of Python Virtual Machine (PVM) is to convert the byte code instructions into
machine code so that the computer can execute those machine code instructions and display
the final output. To carry out this conversion, PVM is equipped with an interpreter.
The interpreter converts the byte code into machine code and sends that machine code to the
computer processor for execution. Since interpreter is playing the main role, often the Python
Virtual Machine is also called an interpreter.
Memory Management in Python

4|Page
BCA – Sem 5 Python Programming CC-302

In C or C++, the programmer should allocate and deallocate (or free) memory dynamically,
during runtime. For example, to allocate memory, the programmer may use malloc() function
and to deallocate the memory, he may use the free() function. But inPython, memory allocation
and deallocation are done during runtime automatically. The programmer need not allocate
memory while creating objects or deallocate memory when deleting the objects.
Memory management
Everything is considered as an object in Python. For example, strings are objects. Lists are
objects. Functions are objects. Even modules are also objects. For every object, memory should
be allocated.
Memory manager inside the PVM allocates memory required for objects created in a Python
program. All these objects are stored on a separate memory called heap. Heap is the memory
which is allocated during runtime. The size of the heap memory depends on the Random Access
Memory (RAM) of our computer and it can increase or decrease its size depending on the
requirement of the program.
Following Figure shows the allocation of memory by Python's Virtual Machine:

We know that the actual memory (RAM) for any program is allocated by the underlying
Operating system.
On the top of the Operating system, a raw memory allocator oversees whether enough memory
is available to it for storing objects.
On the top of the raw memory allocator, there are several object-specific allocators operate on
the same heap. These memory allocators will implement different types of memory
management policies depending on the type of the objects.
For example, an integer number should be stored in memory in one way and a string should be
stored in a different way. Similarly, when we deal with tuples and dictionaries, they should be
stored differently. These issues are taken care of by object-specific memory allocators.

Python Garbage Collection


A module represents Python code that performs a specific task. Garbage collector is a module
in Python that is useful to delete objects from memory which are not used in the program.
The module that represents the garbage collector is named as gc. Garbage collector in the
simplest way to maintain a count for each object regarding how many times that object is
referenced (or used).
When an object is referenced twice, its reference count will be 2.
When an object has some count, it is being used in the program and hence garbage collector
will not remove it from memory.
When an object is found with a reference count 0, garbage collector will understand that the
object is not used by the program and hence it can be deleted from memory.
Hence, the memory allocated for that object is deallocated or freed.

Python versus C Language


5|Page
BCA – Sem 5 Python Programming CC-302

The following are the major differences from the python to C Language
C language Python Language
C is procedure-oriented programming
Python is object-oriented oriented language. It
language.It does not contain the features like
contains features like classes, objects,
classes, objects, inheritance, polymorphism,
inheritance, polymorphism, etc.
etc.
Pointers concept is available in C. Python does not use pointers.
C has do… while, while and for loops. Python has while and for loops.
C has 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.
Python programs are slower compared to C.
C programs execute faster. 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.
C language type discipline is static and
Python type discipline is dynamic and strong.
weak.
C does not have exception handling facility Python handles exceptions and hence Python
and hence C programs are weak. programs are robust.
The programmer should allocate and
Memory allocation and deallocation is done
deallocate memory using malloc(), calloc(),
automatically by PVM.
realloc() or free() functions.
Automatic garbage collector is available in
C does not contain a garbage collector.
Python.
Python supports only single dimensional
C supports single and multi-dimensional arrays. To work with multi-dimensional arrays,
arrays. we should use third party applications like
numpy.
Array index can be positive or negative integer
The array index should be positive integer. number. Negative index represents locations
from the end of the array.
Checking the location outside the allocation Python performs checking outside an array for
of an array is not supported in C. all iterations while looping.
C supports in-line assignments. Python does not support in-line assignments.
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 separator.
separate expressions.
Indentation of statements is not necessary in Indentation is required to represent a block of
C. statements.

6|Page
BCA – Sem 5 Python Programming CC-302

Python versus Java Language


The following are the major differences from the python to Java Language
Java Language Python Language
Java is object-oriented programming
Python blends the functional programming with
language. Functional programming
object-oriented programming features. Lambdas
features are introduced into Java 8.0
are already available in Python.
through lambda expressions.
Java language type discipline is static and
Python type discipline is dynamic and strong.
weak.
It is compulsory to declare the datatypes of
Type declaration is not required in Python.
variables, arrays etc. in Java.
Python programs are concise and compact. A big
Java programs are verbose. It means they
program can be written using very less number of
contain more number of lines.
lines.
In Java, the collection objects like Stack,
Python collection objects like lists and dictionaries
LinkedList or Vector store only objects but
can store objects of any type, including numbers
not primitive datatypes like integer
and lists.
numbers.
Memory allocation and deal location is
Memory allocation and deal location is done
done automatically by JVM (Java Virtual
automatically by PVM (Python Virtual Machine).
Machine).
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.
A semicolon is used to terminate the
New line indicates end of the statements and
statements and comma is used to separate
semicolon is used as an expression separator.
expressions.
Indentation of statements is not necessary Indentation is required to represent a block of
in Java. statements.
Java has do… while, while, for and for
Python has while and for loops.
each loops.
Java has switch statement or block. Python does not have switch statement or block.
Python supports only single dimensional arrays. To
Java supports single and multi-
work with multi-dimensional arrays, we should use
dimensional arrays.
third party applications like numpy.
Array index can be positive or negative integer
The array index should be a positive
number. Negative index represents locations from
integer.
the end of the array.
Checking the location outside the
Python performs checking outside an array for all
allocation of an array is not supported in
iterations while looping.
Java.

7|Page
BCA – Sem 5 Python Programming CC-302

PYTHON PROGRAM EXECUTION


There are three ways of executing a Python program

1. Using Python's command line window


2. Using Python's IDLE graphics window
3. Directly from System prompt

Simple Program :
num1=10
num2=20
print(“The Sum :”(a+b))
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.

Comments in Python
There are two types of comments in Python

1. Single line comments


2. Multi line comments

Single line comments


These comments start with a hash symbol (#) and are useful to mention that the entire line till
the end should be treated as comment
Example :# To find the sum of two number
A=10 # Variable A stores the value 10.
Multi line comments
When we want to mark several lines as comment, then writing #symbol in the beginning of
every line will be a tedious job.
Instead of starting every line with #symbol, we can write the previous block of code inside """
(triple double quotes) or ''' (triple single quotes) in the beginning and ending of the block as:
The triple double quotes (""") or triple single quotes (''') are called 'multi line comments' or
'block comments'. They are used to enclose a block of lines as comments.

8|Page

You might also like