0% found this document useful (0 votes)
1 views31 pages

Python programming session 1_Introduction

The document provides an overview of Python programming, covering its history, features, and memory management. It explains the differences between interpreters and compilers, the concept of bytecode, and the role of the Python Virtual Machine (PVM). Additionally, it discusses memory allocation methods, garbage collection, and reference counting in Python.

Uploaded by

Aahaan Phadnis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views31 pages

Python programming session 1_Introduction

The document provides an overview of Python programming, covering its history, features, and memory management. It explains the differences between interpreters and compilers, the concept of bytecode, and the role of the Python Virtual Machine (PVM). Additionally, it discusses memory allocation methods, garbage collection, and reference counting in Python.

Uploaded by

Aahaan Phadnis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PYTHON PROGRAMMING

(Electronics Engineering), SEMESTER – III


Course Code (R4EC2005T)

By
Prof. Sonal Gedam
VJTI, MUMBAI
What is Python?
Python is an example of a high-level language; other high-level
languages you might have heard of are C++, PHP, and Java.

• Multi-purpose (Web, GUI, Scripting, etc.)


• Object Oriented
• Interpreted
• Strongly typed and Dynamically typed
• Focus on readability and productivity
History of Python:
• Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherland
• 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 is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python
• 2.7.11 is the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the removal
of duplicate programming constructs and modules so that "There should be
one -- and preferably only one -- obvious way to do it." Python 3.5.1 is the
latest version of Python 3
Features of python:
Python's features include-

Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a student to pick up the language quickly.

Easy-to-read: Python code is more clearly defined and visible to the eyes.

Easy-to-maintain: Python's source code is fairly easy-to-maintain.

A broad standard library: Python's bulk of the library is very portable and cross
platform compatible on UNIX, Windows, and Macintosh.

Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

Databases: Python provides interfaces to all major commercial databases.

GUI Programming: Python supports GUI applications that can be created and
ported 4 to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.

Scalable: Python provides a better structure and support for large programs
than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features.
A few are listed below-

• It supports functional and structured programming methods as well as OOP.

• It can be used as a scripting language or can be compiled to byte-code for


building large applications.

• It provides very high-level dynamic data types and supports dynamic type
checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Interpreter VS Compiler

Two kinds of applications process high-level languages into low-level languages:


interpreters and compilers.

An interpreter reads a high-level program and executes it, meaning that it does
what the program says. It processes the program a little at a time, alternately
reading lines and performing computations.

A compiler reads the program and translates it into a low-level program, which
can then be run.
In this case, the high-level program is called the source code, and the
translated program is called the object code or the executable. Once a
program is compiled, you can execute it repeatedly without further translation
Many modern languages use both processes. They are first compiled into a
lower level language, called byte code, and then interpreted by a program called
a virtual machine. Python uses both processes, but because of the way
programmers interact with it, it is usually considered an interpreted language

There are two ways to use the Python interpreter:


shell mode and script mode.
In shell mode, you type Python statements into the Python shell and the
interpreter immediately prints the result.
In this course, we will be using an IDE (Integrated Development Environment)
called IDLE. When you first start IDLE it will open an interpreter window.1

The first few lines identify the version of Python being used as well as a few
other messages; you can safely ignore the lines about the firewall.

Next there is a line identifying the version of IDLE. The last line starts with >>>,
which is the Python prompt. The interpreter uses the prompt to indicate that it
is ready for instructions.
If we type print 1 + 1 the interpreter will reply 2 and give us another prompt.2
Running Python program:

There are three different ways to start Python-

(1) Interactive Interpreter


You can start Python from Unix, DOS, or any other system that provides you
a command line interpreter or shell window.
Enter python the command line.

(2) Script from the Command-line

(3) Integrated Development Environment


What is Debugging ?

Programming is a complex process, and because it is done by human beings,


programs often contain errors. For whimsical reasons, programming errors are
called bugs and the process of tracking them down and correcting them is
called debugging.

Three kinds of errors can occur in a program: syntax errors, runtime errors, and
semantic errors. It is useful to distinguish between them in order to track them
down more quickly
Syntax errors

Python can only execute a program if the program is syntactically correct;


otherwise, the process fails and returns an error message. Syntax refers to the
structure of a program and the rules about that structure. For example, in English,
a sentence must begin with a capital letter and end with a period. this sentence
contains a syntax error.
So does this one For most readers, a few syntax errors are not a significant
problem, which is why we can read the poetry of e. e. cummings without spewing
error messages. Python is not so forgiving. If there is a single syntax error
anywhere in your program, Python will print an error message and quit, and you
will not be able to run your program.
During the first few weeks of your programming career, you will probably spend a
lot of time tracking down syntax errors. As you gain experience, though, you will
make fewer syntax errors and find them faster.
Runtime errors
The second type of error is a runtime error, so called because the error does not
appear until you run the program. These errors are also called exceptions because
they usually indicate that something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in the first few
chapters, so it might be a while before you encounter one.

Semantic errors
The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully, in the sense that the computer will not generate
any error messages, but it will not do the right thing. It will do something else.
Specifically, it will do what you told it to do.
The problem is that the program you wrote is not the program you wanted to
write. The meaning of the program (its semantics) is wrong. Identifying semantic
errors can be tricky because it requires you to work backward by looking at the
output of the program and trying to figure out what it is doing.
Bytecode
Machines are not able to understand the human language or high-level
languages thus whenever we write code in any programing language, machine
used a compiler or an interpreter to convert the human-readable code to
machine code. When the code is converted to machine code a new file is
created which is easier for a machine to understand and execute. Such files
contain code in bytes which is the machine-readable format.
Byte codes are referred to as the portable codes or p-codes. When a python
code is interpreted into the machine language then the python code gets
converted into bytes. These bytecodes are also called as the set of instructions
for the virtual machine and the python interpreter is the implementation of the
virtual machine. The set The intermediate format is called the bytecode.
Bytecodes are :

• Lower-level
• Platform Independent
• Efficient
• Intermediate
• Representation of source code
Bytecode is the low-level representation of the python code which
is the platform-independent, but the code is not the binary code
and so it cannot run directly on the targeted machine.
It is a set of instructions for the virtual machine which is also called
as the Python Virtual Machine[PVM]. When the Python code is
interpreted it is converted to the compiled bytecode file referred
to as the PYC file. Pyc files have the set of instructions to follow in
sequence to generate the output. These pyc files are faster than
the normal python code files
Bytecodes in pyc files
Python programing language is an interpreter language which converts the
python code to the bytecode. These bytecodes are created by a compiler
present inside the interpreter. Interpreter first compiles the python code to the
byte code which is also called as the intermediate code, then the code is used
to run on the virtual machine. In the virtual machine, the library modules of the
python get added and then the code is ready to run on a machine. Steps for
interpretation of python source code:

Source code: Python Code


Compiler: Enters inside the compiler to generate the bytecode
Bytecode: Intermediate code or low-level code
Virtual Machine: Here the code gets the support from the library modules.

Python is slower as compared to another programing language, but the process


of converting the python code to the bytecode makes it faster to access each
time after the code is interpreted once. This bytecode is saved in the file named
same as the source file but with a different extension named as “pyc”.
Python Virtual Machine
• Python Virtual Machine (PVM) is a program which provides
programming environment.
• The role of PVM is to convert the byte code instructions into
machine code so the computer can execute those machine code
instructions and display the Output.
• Interpreter converts the byte code into machine code and sends
that machine code to the computer processor for execution.
• 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.
• 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 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.
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 is very important for software developers
to work efficiently with any programming language. As we
know, Python is a famous and widely used programming
language. It is used almost in every technical domain. In
contrast to a programming language, memory management is
related to writing memory-efficient code. We cannot overlook
the importance of memory management while implementing a
large amount of data. Improper memory management leads to
slowness on the application and the server-side components. It
also becomes the reason of improper working. If the memory is
not handled well, it will take much time while preprocessing the
data.
In Python, memory is managed by the Python manager which
determines where to put the application data in the memory.
So, we must have the knowledge of Python memory manager
to write efficient code and maintainable code.
Let's assume memory looks like an empty book and we want to
write anything on the book's page. Then, we write data any
data the manager find the free space in the book and provide it
to the application. The procedure of providing memory to
objects is called allocation.
On the other side, when data is no longer use, it can be deleted
by the Python memory manager. But the question is, how? And
where did this memory come from?
Python Memory Allocation

Memory allocation is an essential part of the memory


management for a developer. This process basically allots free
space in the computer's virtual memory, and there are two
types of virtual memory works while executing programs.

Static Memory Allocation


Dynamic Memory Allocation
Static Memory Allocation

Static memory allocation happens at the compile time. For


example - In C/C++, we declare a static array with the fixed
sizes. Memory is allocated at the time of compilation.
However, we cannot use the memory again in the further
program.
Stack Allocation
• The Stack data structure is used to store the static memory.
• It is only needed inside the particular function or method
call. The function is added in program's call stack whenever
we call it.
• Variable assignment inside the function is temporarily
stored in the function call stack; the function returns the
value, and the call stack moves to the text task.
• The compiler handles all these processes, so we don't need
to worry about it.
• Call stack (stack data structure) holds the program's
operational data such as subroutines or function call in the
order they are to be called. These functions are popped up
from the stack when we called.
Dynamic Memory Allocation

Unlike static memory allocation, Dynamic memory allocates


the memory at the runtime to the program.
For example - In C/C++, there is a predefined size of the
integer of float data type but there is no predefine size of the
data types.
Memory is allocated to the objects at the run time. We use
the Heap for implement dynamic memory management. We
can use the memory throughout the program.
Everything in Python is an object means dynamic memory
allocation inspires the Python memory management. Python
memory manager automatically vanishes when the object is no
longer in use.

Heap Memory Allocation


Heap data structure is used for dynamic memory which is not
related to naming counterparts. It is type of memory that uses
outside the program at the global space. One of the best
advantages of heap memory is to it freed up the memory space
if the object is no longer in use or the node is deleted.
Python Garbage Collector
Python removes those objects that are no longer in use or can say that it
frees up the memory space. This process of vanish the unnecessary object's
memory space is called the Garbage Collector. The Python garbage collector
initiates its execution with the program and is activated if the reference
count falls to zero.
When we assign the new name or placed it in containers such as a
dictionary or tuple, the reference count increases its value. If we reassign
the reference to an object, the reference counts decreases its value. It also
decreases its value when the object's reference goes out of scope or an
object is deleted.
Python uses the dynamic memory allocation which is managed by the Heap
data structure. Memory Heap holds the objects and other data structures
that will be used in the program. Python memory manager manages the
allocation or de-allocation of the heap memory space through the API
functions.
Python Objects in Memory
The object can either be simple (containing numbers, strings,
etc.) or containers (dictionary, lists, or user defined classes). In
Python, we don't need to declare the variables or their types
before using them in a program.

As we can see in the above output, we


assigned the value to object x and
printed it. When we remove the object x
and try to access in further code, there
will be an error that claims that the
variable x is not defined. Hence, Python
garbage collector works automatically
and the programmers doesn't need to
worry about it, unlike C.
Reference Counting in Python
Reference counting states that how many times other objects
reference an object. When a reference of the object is assigned,
the count of object is incremented one. When references of an
object are removed or deleted, the count of object is
decremented. The Python memory manager performs the de-
allocation when the reference count becomes zero. Let's make it
simple to understand.
Suppose, there is two or more variable that contains the same
value, so the Python virtual machine rather creating another
object of the same value in the private heap. It actually makes
the second variable point to that the originally existing value in
the private heap.
This is highly beneficial to preserve the memory, which can be
used by another variable.

You might also like