Python CHAP1
Python CHAP1
PYTHON PROGRAMMING
Chapter 1
brief history; features; applications of python; python distributions; versions; python IDEs; Python
interpreter; Execution of python programs, debugging python code; Indentation, Comments; best
practices for python programming; Character set; tokens; keywords, variables, naming rules for
variables, Assignment.
1.1 Introduction
Python is an interpreter, high level general purpose programming language. Created by Guido van Rossum
during 1985-1990. Work on Python began in late 1989 by Guido van Rossum, then at CWI (Centrum voor
Wiskunde en Informatica, the National Research Institute for Mathematics and Computer Science) in the
Netherlands. It was eventually released for public distribution in early 1991.
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 is a general purpose, dynamic, high-level, and interpreted programming language. It supports
Object Oriented programming approach to develop applications. It is simple and easy to learn and
provides lots of high-level data structures.
● Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
● Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting
and rapid application development.
● Python supports multiple programming pattern, including object-oriented, imperative, and functional or
procedural programming styles.
● Python is not intended to work in a particular area, such as web programming. That is why it is known
as multipurpose programming language because it can be used with web, enterprise etc.
● We don't need to use data types to declare variable because it is dynamically typed so we can write
a=10 to assign an integer value in an integer variable.
● Python makes the development and debugging fast because there is no compilation step included in
Python development, and edit-test-debug cycle is very fast.
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
1.2 Python Features:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the
student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
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.
GUI Programming − Python supports GUI applications that can be created and ported 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, few are listed below −
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 can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the fastest-growing
programming language and can develop any application.
Here, we are specifying application areas where Python can be applied.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such as
HTML and XML, JSON, Email processing, request, beautiful Soup, Feed parser, etc. One of Python
web-framework named Django is used on Instagram. Python provides many useful frameworks, and
these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application.
Python provides a Tk GUI library to develop a user interface. Some popular GUI libraries are given
below.
o Tkinter or Tk
o wxWidgetM
o PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the old
generation of computers. Python can develop this kind of application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the
command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console help text
out-of-the-box. There are also advance libraries that can develop independent console apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can be used to
build control and management, testing, etc.
o Buildbot and Apache Gumps are used for automated continuous compilation and testing.
This is the era of Artificial intelligence where the machine can perform the task the same as the human.
Python language is the most suitable language for Artificial intelligence or machine learning. It consists
of many scientific and mathematical libraries, which makes easy to solve complex calculations.
Implementing machine learning algorithms require complex mathematical calculation. Python has many
libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some
basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks
of machine libraries are given below.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example of a
business application. This kind of application requires extensively, scalability and readability, and Python
provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business application.
Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some
multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few multimedia
libraries are given below.
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by using the
following functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an Organization. Some
real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be manipulated
according to our requirements. Some libraries of image processing are given below.
o OpenCV
o Pillow
o SimpleITK
Python 1.0 January 1994 Functional programming tools (lambda, map, filter and
reduce).
Support for complex numbers.
Functions with keyword arguments
Python 3.9 - Current October 2020 Dictionary Merge & Update Operators
Version New removeprefix() and removesuffix() string methods
Builtin Generic Types
StacklessPython
Tiny Python (archived link) - not to be confused with tinypy
WinPython: Another scientific-focused Python distribution
1.5 Versions:
An IDE (Integrated Development Environment) understand your code much better than a text editor. It
usually provides features such as build automation, code linting, testing and debugging. This can
significantly speed up your work. The downside is that IDEs can be complicated to use.
2. IDLE
For: Beginner Pricing: Free
When you install Python, IDLE is also installed by default. This makes it easy to get started in Python.
Its major features include the Python shell window (interactive interpreter), auto-completion, syntax
highlighting, smart indentation, and a basic integrated debugger.
3. Sublime Text 3
For: Beginner, Professional Pricing: Freemium
Sublime Text is a popular code editor that supports many languages including Python. It's fast, highly
customizable and has a huge community.
It has basic built-in support for Python when you install it. However, you can install packages such as
debugging, auto-completion, code linting, etc. There are also various packages for scientific
development, Django, Flask and so on. Basically, you can customize Sublime text to create a full-
fledged Python development environment as per your need.
4. Atom
Atom is an open-source code editor developed by Github that can be used for Python development .Its
features are also similar to Sublime Text. Atom is highly customizable. You can install packages as
per your need. Some of the commonly used packages in Atom for Python development are
autocomplete-python, linter-flake8, python-debugger, etc.
5. Thonny
Thonny is a Python dedicated IDE that comes with Python 3 built-in. Once you install it, you can start
writing Python code.
Thonny is intended for beginners. The user interface is kept simple so that beginners will find it easy
to get started.it has several useful features that also make it a good IDE for full-fledged Python
development. Some of its features are syntax error highlighting, debugger, code completion, step
through expression evaluation, etc.
6. PyCharm
PyCharm is an IDE for professional developers. It is created by JetBrains, a company known for
creating great software development tools.
Community - free open-source version, lightweight, good for Python and scientific development
Professional - paid version, full-featured IDE with support for Web development as well
PyCharm provides all major features that a good IDE should provide: code completion, code
inspections, error-highlighting and fixes, debugging, version control system and code refactoring. All
these features come out of the box.
Visual Studio Code (VS Code) is a free and open-source IDE created by Microsoft that can be used for
Python development.
You can add extensions to create a Python development environment as per your need in VS code. It
provides features such as intelligent code completion, linting for potential errors, debugging, unit
testing and so on.
VS Code is lightweight and packed with powerful features. This is the reason why it becoming popular
among Python developers.
8. Vim
Vim is a text editor pre-installed in macOS and UNIX systems. For Windows, you need to download
it.
If you already know how to use Vim, it can be a good tool for Python development. If not, you need to
invest time learning Vim and its commands before you can use it for Python.
You can add plugins for syntax highlighting, code completion, debugging, refactoring, etc. to Vim and
use it as a Python IDE.
9. Spyder
The easiest way to get up and running up with Spyder is by installing Anaconda distribution. If you
don't know, Anaconda is a popular distribution for data science and machine learning. The Anaconda
distribution includes hundreds of packages including NumPy, Pandas, scikit-learn,matplotlib and so
on.
Spyder has some great features such as autocompletion, debugging and iPython shell. However, it
lacks in features compared to PyCharm.
On Windows machines where you have installed Python from the Microsoft Store,
the python3.10 command will be available. If you have the py.exe launcher installed, you can use
the py command.
You can start Python from Unix, DOS, or any other system that provides you a command-line
interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1 -d
It provides debug output.
2 -O
It generates optimized bytecode (resulting in .pyo files).
3 -S
Do not run import site to look for Python paths on startup.
4 -v
verbose output (detailed trace on import statements).
5 -X
disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.
6 -c cmd
run Python script sent in as cmd string
7 file
run Python script from given file
A Python script can be executed at command line by invoking the interpreter on your application, as in
the following −
$python script.py # Unix/Linux
or
or
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI
application on your system that supports Python.
Unix − IDLE is the very first Unix IDE for Python.
Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
Import pdb
pdb.set_trace()
n=5
for x in range(1,11) :
1.10 Indentation:
Indentation is a very important concept of Python because without proper indenting the Python code,
you will end up seeing IndentationError and the code will not get compiled.
In simple terms indentation refers to adding white space before a statement. But the question arises is
it even necessary?
To understand this consider a situation where you are reading a book and all of a sudden all the page
numbers from the book went missing. So you don’t know, where to continue reading and you will get
confused. This situation is similar with Python. Without indentation, Python does not know which
statement to execute next or which statement belongs to which block. This will lead
to IndentationError.
Ex:
if a==1:
print(a)
if b==2:
print(b)
print('end')
In the above code, the first and last line of the statement is related to the same suite because there is no
indentation in front of them. So after executing first "if statement", the Python interpreter will go into
the next statement. If the condition is not true, it will execute the last line of the statement.
At the next level, the following statements are typed with four spaces (a tab) in front of them, and so
they are in the same suite.
Example:
print(a)
if b==2:
The third statement: "if b==2" will be executed if the first statement: "if a==1" is true.
In the next statement, eight spaces (two tabs) have been typed in front of "print (b)", and hence it is in
a separate suite, and it will execute only if the statement "if b==2" is true.
print(b)
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
1.11 Comments:
Comments can be used to make the code more readable. Comments starts with a #, and Python will
ignore them:
Example
#This is a comment
print("Hello, World!")
Example
Python does not really have a syntax for multi line comments. To add a multiline comment you could
insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and
you have made a multiline comment.
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters
only.
assert finally or
def if return
elif in while
else is with
1.15 Variables:
Variables are reserved memory locations to store values. This means that when you create a variable
you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals or characters in these variables.
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the
= operator is the value stored in the variable. For example −
Ex:
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print mile
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result −
100
1000.0
John
Multiple Assignments
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.
------------------------************************************------------------------