Python
Python
Python
Python Programming
Dr. M Swamy Das, Department of Computer
Science and Engineering, CBIT, 2017-18
Features of Python
● Python is an exciting and powerful language with performance of
and features
● Features of Python
– Simple -simple and small language
– Easy to learn – programs are readable, simple structure
– Versatile- supports development of a wide range of applications ranging
from simple text processing to www browsers to games
– High-level language- doesn’t require low level details
– Interactive – allows interactive testing & debugging pieces of code,
interact
– Portable – cross platform Linux, Windows, FreeBSD, Macintosh, OS/2,
AROS, AS/400, BeOS, OS/390, z?OS, Palm OS, QNX, Psion, Acorn
RISC, VxWorks, PlayStation, Sharp Zaurus, Windows CE, packet PC
– Object-Oriented – Its like C++, Java etc.
– Interpreted – simpler execute cycle and works faster
Features of Python (cont.)
– Dynamic – executes dynamically
– Extensible – any one can add low level modules
– Embeddable – C, C++, COM, ActiveX, CORBA and Java
programs can be embedded
– Extensive Libraries – Huge library portable with different platforms
● Good features
– Easy maintenance
– Secure
– Robust
– Multi-threaded
– Garbage Collection
Limitations of Python
● Parallel processing can be done in Python but not as like
JavaScript and Go Lang.
● Python is not a very good choice for those developing a high-
graphic 3D game that takes up a lot of CPU
● Little documentation
● Few users compared to C, C++ or Java
● It lacks true multi-processor support
● It has very limited commercial support point
● Slower than C or C++ when it comes to computation of heavy
tasks and desktop applications
● It is difficult to pack up a big Python application into a single
executable file. So it is difficult to distribute to non-technical users
History
● Developed by Guido van Rossum in the late 80’s and early 90’s
at National Research Institute for Mathematics and Computer
Science, Netherlands
● Derived from many languages such as ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell and other scripting languages
● Version 1.0 released in 1991, current Python version is 3.6.4
● Source code is available under GNU GPL
● Python is older than Java, R and JavaScript
Applications of Python
● Python is used to develop a wide range of applications including
Image Processing, Text Processing, Web and Enterprise level
applications using the scientific and numeric data frame work
– Embedded scripting language: used for testing/ building/
deployment/monitoring frameworks, scientific apps, and quick scripts
– 3D Software: Like Maya uses Python for automating small user tasks, or for
doing complex integration such as talking to databases
– Web development: Quora, Odoo, a business application applications and
Google App engine are based on Python
● Frameworks
– Django and Pyramid (web development)
– Flask and Bottle (micro framework) and
– Plone and django CMS (advanced Content Management System)
● Frameworks provide libraries and modules simplifies the content
management, interaction with database and interfacing with different
Internet protocols such as HTTP, SMTP, XML-RPC, FTP and POP
Applications of Python (cont.)
● GUI-based desktop applications: has various tool kits like
– wxPython, PyQt or PyGtk
● IP and Graphic design applications :
– 2D- image software such Inscape, GIMP, Print Shop Pro
Scribus
– 3D- animation packages, like Blender, 3ds Max, Cinema
4D, Houndini, and Maya coded in Python
● Scientific and computational applications
– Scipy (scientific and Engineering) Numpy (Numeric Python),and
pandas(data analysis and modeling library), Ipython -powerful
interactive shell supporting ease of editing and recording a work
session, visualization and parallel computing, FreeCAD, finite element
software, like Abacus are coded in Python
Applications of Python (cont.)
● Games – Civiliztion-IV, Disney’s Toontown, Vega Strike etc. written in
Python
● Enterprise and business applications: provides – Reddit, part of
Youtube code is written in Python
● Operating Systems- Ubuntus’s Ubiquity installer, Fedora’s and
RedHat Enterprise Linux’s Anaconda installer are written in Python
Gentoo Linux uses Python for portage, it package management
● Language development-Used to develop other languages like Boo,
Apples’s Wift, CoffeeScript, Cobra, Ocmal have same
syntax as Python
● Prototyping-agility, extensibility, scalability of code
● Network Programming- socket interface, functions for email
processing, support for FTP, IMAP and other Internet protocols
● Teaching – to teach programming skills
st
Writing and Executing 1 Python Program
● Download Python from www.python.org
● Work from Python console
– Ex: $python
>>> print (“Welcome to LPSL”)
>>> 10 + 15
>>> (456788-57)*5
– +, -, *,/,%, //(floor division), **
Exponentiation
– Ex: 78//5=>15,78%5=>3, 152.78//3.0=>50.0,
152.78%3.0 => 2.780000000000001, 5**=>125,
121**0.5=>11.0
● GUI software – IDLE (install using apt-get install idle)
● Invoke IDLE from terminal ($idle <Enter>)
Strings
● String : Is a group of characters.
● Ways to represent
– Single quotes ( ex: ‘Welcome’)
– Double quotes (ex. “Welcome”, same as single quotes)
– 'Triple quotes – used to specify multi-line strings. Use ‘\’ at the end of line to
print in the same line
>>> print '''Welcome to
LPSL'''
Welcome to
LPSL
>>>
– Unicode strings: Standard way of writing international text, like Hindi, Telugu.
Use u or U. ex: print u” UNICODE Text”
– Escape sequence character: use \ to print special chars like \, *, ‘, “ etc.
– To print raw string use ‘R’. ex: >>>print (R “What\’ your name?”);
Formatting
● Format() function is used to control the format of the display
● Syntax: format(value, format_specifier);
– Examples:
>>> format(10/3.0)
'3.33333333333'
>>> format(10/3.0,'.2f')
'3.33'
>>> format('LPSL','<30')
'LPSL '
>>> format("LPSL",'>30')
' LPSL'
– >>> print ('Welcome to LPSL',format('!','*<10'),'BE2/4 CSE-1')
● Comments: # symbol
● Reserved words
– All reserved words or keywords can not be used for naming identifiers and in lower
case
– and, assert, break, class, def, del, elif, else, except, exec,
finally, for, from, global, if, import, in, is, lambda, not,
or, pass, print, raise, return, try, while, with, yield
● Indentation
– White space at the beginning of the line is called ‘indentation’. Important in Python
– Lines at the same level called a block. Python does not use curly braces ({..})
– The symbol ‘^’ represent indentation error
Operators
● Arithmetic (+, -, *, %, /, **, //)
● Relational (==, !=, <, >, <=, >=)
● Assignment and in-place or shortcut operators (=, =+, -=, *=, %=,
/=, **=, //=)
40+(20*30)/10 = ??
● Logical (&&, ||, ! )
10+3*4+2**6-10 =??
● Unary (-)
● Bitwise(&, |, ^, ~, <<, >>)
● Membership (in, not in)
● Identity (is, is not)
Expressions
● Operand: is the value on which operator is applied. Operands can be
constants and variables
● Expression : Collection of operands and operators.
Ex: c = a+ b +10
● Types of expressions
– constant (67+10), Integral, floating point,
– relational,
– logical, bitwise, assignment
● Based on the type of the operands, expressions are evaluated
● Operations on strings: concatenation (+), string multiplication or
repetition (*), string slicing [] and [:])
Tuples
● Sequences: allow to store multiple values in an organized way
● Sequences are
– Tuples
– Lists and
– Strings
● Tuple: Similar to lists as it also consists of a number of elements
separated by commas and enclosed within parentheses.
– It is an unchangeable or a constant list. A tuple cannot be changed once
it is created. (len() fnction can be used to find the length of a tuple)
tuples(cont.)
● Packing
>>>rec=’733001’, ‘Ramya’, 23
>>>rec
(’733001’, ‘Ramya’, 23)
● Unpacking:
>>>rno,name,rank=rec
>>>Name,rank,rno
('Ramya', 12, '733001')
● Variables on the left hand side should be equal to the tuple
length
Lists
●
Lists are versatile data types of Python language
●
A list consists of items separated by commas and enclosed in
square brackets ([ ])
● Lists are similar to C/C++/Java arrays; list items in Python can have
values belonging to different types
●
Values in stored in a list are accessed using indexes (0..n-1, where
n is the number of elements)
●
Slice, concatenation and repetition operators can be applied on lists
– Example:
>>>L=[8, ‘P’, “Good Morning”, 67, 45.67]
>>>a=9
>>> b=20
>> L=[a+b, b-a, a-c]
List operations (cont.)
● Other operations:
– insert : list.insert(i, x) :insert x at position ‘i’ in the list
– Deletion of items from the list
● list.remove(x): remove the 1st occurrence of the element ‘x’ from the list
● list.pop(): removes the last element from the list
● list.pop(0): removes the 1st element from the list
– append: list.append(x): appends the element at the end of the list
– extend: list.extend (L): extends the existing list by appending all items of list ‘L ‘
– retrieve: list.index(x): Returns the index of the 1st occurrence of item ‘x’ in the
list
– sort: list.sort(x): arrange the items in the list in order
– reverse: list.sort(x): arrange the items in the list in revers order
– count: list.count(x): returns the number of occurrences of item ‘x’ in the list
– length: list.len(): Returns the number of items in the list
example
Dictionaries
● Dictionaries store data in key-value pairs, where key values are usually
strings and ca be of any data type
● Key-value pairs are enclosed with curly braces ( { } ) and each key value
is separated by a colon
● To access any value in the dictionary, we need to specify its key in square
braces([] )
● Dictionaries are used for fast retrieval of data
● Lists and dictionaries are mutable data types. i.e. their values can be
changed
● Example:
Dict = { “1601”: “CBIT”, “Location”: “Gandipet”, “rank”: 1}
print (Dict[“1602”])
print (Dict[‘Location’])
Output will be
CBIT
Gandipet
Type Conversion
Function Description
int(x) Converts x to an integer (truncates, don’t round)
long(x) Converts x to a long integer
float(x) Converts x to a floating point number
str(x) Converts x to a string
tuple(x) Converts x to a tuple
list(x) Converts x to a list
set(x) Converts x to a set
ord(x) Converts a single character to an integer value
oct(x) Converts an integer to an octal string
hex(x) Converts an integer to a hexadecimal string
unichr(x) Converts an integer to a Unicode character
dict(x) Converts a dictionary if x forms a (key-value) pair
Decision Control Structures
●
Control statements determine the control flow of a set of instructions
● Fundamental methods of control flow are
– Sequential
– Selection (if, if .. else, nested if, if-elif-else)
– Iterative (while, for)
●
if statement
if test_expression:
statement 1
..
statement n
● Example:
x=int(input(‘Enter a number: ‘))
rem=x%2
if (rem==0):
print( x ‘x=x+1
print (x)
if..else and if-elif-else
#script to check whether a given number
if test_expression: # is +ve, -ve or equal to 0
statement block1 n = input('Enter a number: ')
if (n == 0):
else: print(str(n)+ ' is zero')
statement block2 elif (n>0):
print(str(n)+ ' is +ve')
else:
print(str(n)+ ' is -ve')
if (test_expression):
statement block1 #largest of given 3 numbers
a = int(input('Enter the 1st number: '))
elif (test_expression 2): b = int(input('Enter the 2nd number: '))
statement block2 c = int(input('Enter the 3rd number: '))
.. if(a>b):
if(a>b):
elif (test_expression N): print(a, 'is greater than',b,'and', c)
statement block N else:
print(c, 'is greater than',a,'and', b)
else: elif b>c:
statement block X print(b, 'is greater than',a,'and', c)
statement Y else:
print(c, 'is greater than',a,'and', b)
Loop/ Iterative Structures
● While: repeat one of more statements while a particular
condition is True.
● Syntax: #script to print 1st 10 namtural numbers
Statement x count = 0
while count<=10:
While (condition):
print (count)
Statement block count = count +1
Statement Y
class xyz:
def __init__(self, var1,var2):
self.var1=var1;
self.var2=var2; #private class variable
def display(self):
print ('var1: '+str(self.var1))
print ('var2: '+str(self.var2))
obj=xyz(20,26.50)
obj.display()
print ('object.__dict__ : '+str(obj.__dict__))
print ('object.__doc__ : '+str(obj.__doc__))
Class methods and Static Methods
● Class methods
– Different from ordinary methods
– Called by a class(nt by instance of the class)
– 1st argument of the class method is the ‘cls’, not the ‘self’.
– Class methods are widely used for factory methods, which instantiate an
instance of a class using different parameters from those usually passed to the
class constructor
– @classmethod
● Static methods
– Special case methods
– Any functionality that belongs to a class, but that does not require the object
– @staticmethod
Modules
● Modules are pre-written pieces of code that are
used to perform common tasks like generating random
numbers, performing mathematical operations etc.
● A module is file like a file with a .py extension that has
definitions of all functions and variables that we would
like to use even in other programs
● The basic way to use a module is to add import
module_name as the first line of your script and then
writing import module_name.var to access functions
and values with the name var in the module
import sys
print "\nPYTHONPATH = \n",sys.path
Modules (cont.)
● Modules loading and Execution:
– Must be located and loaded into memory before it can be used
– Check in the current directory and then check in the PYTHONPATH environment
variable. Still it is not found then it checks the Python installation-specific path
(like c:\Python34\Lib). Otherwise it raises an ImportError
– To add our modules to be available to other programs , should be stoed in the
directory specified PYTHONPATH.
– Once a module is loaded, then a compiled version of the module with the
extension .pyc is generated. Next time when it is imported then the compiled
version will be loaded
● from .. import statement: when a module is imported, then all the
functions and variable will be loaded. If we want only certain variables
or functions then from import statement is used
a = -200
print (“a = “,a)
a=abs(a)
print (“abs(a) = “,a)
print (“Cube of 200= “, cube(a))
For I in range(10):
value = random.rand(1,100)
print (value)
Standard Library Modules (Python STL)
● Python supports three types of modules
– Written by the programmer
– Installed from external sources and
– Preinstalled with Python
● Standard library: Modules that are pre-installed in Python are
called standard library
– Some useful modules in the standard library
● string, re, datetime, math, random, os, multiprocessing,
subprocess, socket, email, json, doctest, unittest, pdb,
argparse and sys.
● We can use these modules for performing tasks like string parsing, data
serializations, testing, debugging and manipulating dates, emails, command line
arguments etc.
#program to display the date and time using the time module
import time
localtime = time.asctime(time.localtime(time.time()))
print(“Local current time: “, localtime)
globals(), locals() and reload()
● Used to return the global, local namespaces and reload the modules.
● Result of these functions depends on the location from where they
are called
● If locals() is called within a function, names that can be accessed
locally from that function will be returned
● If globals() is called from within a function, all the names that can
be accessed globally from that functions is returned
– Both the functions return using dictionary
● reload(): when a module is imported into a program, the code in
the module is executed only once. If we want to to re-execute the top-
level code in a module, we must use the reload() function.
– reload (module_name)
File Handling
● A file is a collection of data stored on a secondary storage device like
hard disk.
● File are arranged in a hierarchical manner. Accessed by using their
path i.e. relative or absolute.
● File types:
– ASCII files (text files)
● Stream of characters that can be sequentially processed by a computer in forward
direction
● Each character or digit or symbol is stored a byte
● In a text file, each line of data ends with newline character and each file ends with a
special character called the end-of-file (EOF) marker.
– Binary files
● Contain any type of data
● It includes word processor documents, PDFs, images, spreadsheets, videos, zip files
and other executable programs
● Integers are stored as number rather than individual chars.
Opening and closing of files
● Python has many built-in functions and methods to manipulate files
● Open(): used to open or create a new file:
– fileobject = open (filename [,access_mode])
● access_mode indicates the mode in which the file has to be opened. It can
either read, write, append etc.
Mode Purpose
r Default mode, opens for reading. Fptr points to the beginning of the file
rb Opens a file for reading only in binary format;
r+ Opens a file for both reading and writing, fp is placed at the beginning of file
rb+ Opens a file for both reading and writing in binary mode
w Opens a file for writing only , fp is placed at the beginning of file
wb Opens a file for writing only in binary mode , fp is placed at the beginning of file
w+ Opens for both reading and writing
a Opens a file for appending, fp points to the end of the file
ab Opens a file for appending in binary mode, fp points to the end of the file
a+ Opens a file for both reading and appending
ab+ Opens a file in binary format for both reading and appending
File object attributes and methods
#srcipt to create a file
● Attributes file=open("file1.py","r")
print(file)
– fileobj.name: returns the name of the file print ("Name of the file: ",
file.name)
– fileobj.mode: returns the access mode print("File opening mode: ",
– fileobj.closed: returns the return status file.mode)
print("File is closed: ",
● Methods file.close)