0% found this document useful (0 votes)
5 views19 pages

Python CHAP1

The document provides an overview of Python programming, including its history, features, applications, distributions, and IDEs. Python is a versatile, high-level programming language known for its ease of use and broad applicability across various domains such as web development, scientific computing, and enterprise applications. It supports multiple programming paradigms and has a rich ecosystem of libraries and frameworks, making it a popular choice for developers.

Uploaded by

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

Python CHAP1

The document provides an overview of Python programming, including its history, features, applications, distributions, and IDEs. Python is a versatile, high-level programming language known for its ease of use and broad applicability across various domains such as web development, scientific computing, and enterprise applications. It supports multiple programming paradigms and has a rich ecosystem of libraries and frameworks, making it a popular choice for developers.

Uploaded by

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

PYTHON PROGRAMMING (20CS21P) 2023_24

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.

1.1.1 Why Python?

● 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.

P a g e | 1 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

● 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.

 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 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 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.

P a g e | 2 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

1.3 Applications of python:

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:

o Django and Pyramid framework(Use for heavy applications)

P a g e | 3 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

o Flask and Bottle (Micro-framework)

o Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

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 Kivy (used for writing multitouch applications )

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 SCons is used to build control.

o Buildbot and Apache Gumps are used for automated continuous compilation and testing.

o Round or Trac for bug tracking and project management.

5) Scientific and Numeric

P a g e | 4 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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.

7) Audio or Video-based Applications

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

P a g e | 5 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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.

10) Image Processing Application

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

1.4 Python distributions:


Aside from the official CPython distribution available from python.org, other distributions based on
CPython include the following:
 ActivePython from ActiveState
 Anaconda from Continuum Analytics
 ChinesePython Project: Translation of Python's keywords, internal types and classes into
Chinese. Eventually allows a programmer to write Python programs in Chinese.
 Enthought's EDM

P a g e | 6 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

 Win9xPython: Backport of mainline CPython 2.6/2.7 to old versions of Windows 9x/NT.


 IPython and its IPyKit variant
 PocketPython
 Portable Python: Run from USB device - no installation needed.
 PyIMSL Studio
 PyPy: a Python implementation in Python.
 Python(x,y): Python(x,y) is a scientific-oriented Python Distribution based on Qt, Eclipse
and Spyder
 PythonForArmLinux
 PythonLabsPython: an old name for the python.org distribution
 PythonwarePython

Version Release Date Important Features

Python 0.9.0 February 1991  Classes with inheritance exception handling


 Functions
 Modules

Python 1.0 January 1994  Functional programming tools (lambda, map, filter and
reduce).
 Support for complex numbers.
 Functions with keyword arguments

Python 2.0 October 2000  List comprehension.


 Cycle-detecting garbage collector.
Python 2.7.0 - EOL - Jan July 2010  Support for Unicode. Unification of data types and
2020 classes

Python 3 December 2008  Backward incompatible.


 print keyword changed to print() function
Python 3.6 December 2016  raw_input() function depreciated
 Unified str/Unicode types.
Python 3.6.5 March 2018  Utilities for automatic conversion of Pytthon 2.x code

Python 3.7.0 May 2018  New C API for thread-local storage


 Built-in breakpoint()
 Data classes
 Context variables

Python 3.8 October 2019  Assignment Expression


 Positional-only parameters

P a g e | 7 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

Version Release Date Important Features

 Parallel filesystem cache for compiled bytecode files

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:

1.6 python IDEs:

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.

1.Online Compiler from Programiz


For: Beginner Pricing: Free
If you want to start writing Python code without investing time installing Python and setting up a
development environment, you can use online Python compiler. You just need the internet and a
browser to get started.

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

P a g e | 8 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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

For: Beginner, Professional Pricing: Free

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

For: Beginner Pricing: Free

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

For: Professional Pricing: Free

PyCharm is an IDE for professional developers. It is created by JetBrains, a company known for
creating great software development tools.

There are two versions of PyCharm:

 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

P a g e | 9 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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.

7. Visual Studio Code

For: Professional Pricing: Free

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

For: Professional Pricing: Free

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

For: Beginner, Professional Pricing: Free

Spyder is an open-source IDE usually used for scientific development.

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.

P a g e | 10 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

Spyder has some great features such as autocompletion, debugging and iPython shell. However, it
lacks in features compared to PyCharm.

1.7 Python interpreter:


Python is also a piece of software called an interpreter. The interpreter is the program you’ll need to
run Python code and scripts. Technically, the interpreter is a layer of software that works between your
program and your computer hardware to get your code running. The Python interpreter is usually
installed as /usr/local/bin/python3.10 on those machines where it is available;

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.

1.8 Execution of python programs:


There are THREE different ways to start Python −

1.8.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.

Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS

Here is the list of all the available command line options –

P a g e | 11 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

Sr.No. Option & Description

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

1.8.2 Script from the Command-line

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

python% script.py # Unix/Linux

or

C: >python script.py # Windows/DOS

P a g e | 12 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

Note − Be sure the file permission mode allows execution.

1.8.3 Integrated Development Environment

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.

1.9 Debugging python code:


Debugging means the complete control over the program execution. Developers use debugging to
overcome program from any bad issues. So debugging is a healthier process for the program and keeps
the diseases bugs far away. Python also allows developers to debug the programs using pdb module
that comes with standard Python by default. We just need to import pdb module in the Python script.
Using pdb module, we can set breakpoints in the program to check the current status. We can Change
the flow of execution by using jump, continue statements. Let’s understand debugging with a Python
program.

Ex: # Python Program to print Multiplication Table

# We want to debug the for loop so we use

# set_trace() call to pdb module

Import pdb

# It means , the Start of Debugging Mode

pdb.set_trace()

n=5

for x in range(1,11) :

print( n , '*' , x , '=' , n*x )

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?

P a g e | 13 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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)

However, the following block generates an ERROR

P a g e | 14 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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

print("Hello, World!") #This is a comment

Multi Line Comments

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!")

Or, not quite as intended, you can use a multiline string.

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

P a g e | 15 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

"""
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.

1.12 Best practices for python programming:


1. Create a Code Repository and Implement Version Control

2. Create Readable Documentation.

3. Follow Style Guidelines.

4. Correct Broken Code Immediately.

5. Use the PyPI Instead of Doing it Yourself.

6. The Zen of Python.

7. Use the Right Data Structures.

8. Write Readable Code

9. Use Virtual Environments

10. Write Object-Oriented Code

11. What Not to Do while Programming in Python

1.13 Python Identifiers

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.

Here are naming conventions for Python identifiers −

 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.

P a g e | 16 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

 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.

1.14 Reserved Words:

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.

and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda yield

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.

P a g e | 17 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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.

Assigning Values to 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"

P a g e | 18 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan


PYTHON PROGRAMMING (20CS21P) 2023_24

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.

------------------------************************************------------------------

P a g e | 19 SHiVA H Y, Selection Grade Lecturer, Smt. L. V. Govt. Polytechnic, Hassan

You might also like