Sie sind auf Seite 1von 61

Unit-V

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')

('Welcome to LPSL', '!**********', 'BE2/4 CSE-1')


Data Types in Python
● Standard data types
– Numbers, string, list, tuple, and dictionary
● Assigning or initializing values to variables
● Need not explicitly declare variables to reserve memory space
● Declaration done automatically when a value is assigned to
the variable using the equal sign(=)
● Examples:
num=10;val="Welcome to LPSL"; x=45.67
print (num,val,x)
(10, 'Welcome to LPSL', 45.67)
● Reassign values to variable
num=10.5;val=4567888; x=45
Multiple assignment
● Python allows us to assign a single value to more than one variable
simultaneously
– Ex: tc=cc=dc=vc=lc=bc=0
● We can also assign different values to multiple variables simultaneously
– Ex: rno,name,marks, rank = 25, “Ram”, 23.5, 3
● We can delete a variable using ‘del’ command
– Ex: del tc
● Multiple assignments on a same line allowed, but single statement is
more readable
● Boolean: It is another data type which can have two values- True or False
● Ex: >>> 4==4
True
>>> “Python” = = “python”
False
Input, Comments, Reserved words
● To work interactively, Input from the user can be given using ‘input’ function
● Example:

● 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

#script to print sum and average of 1st 10 numbers


count = 0
sum = 0
while count<=10:
sum = sum + count
count = count +1
print ('Sum = ' +str(sum))
print ('Average of 1st 10 numbers: ' +str(sum/10.0))
Write a script to read the numbers until -1 is encountered. Also count
the -ve, +ve and zeros entered by the user
for Loop
● Repeat a task until a particular condition is True.
● Syntax:
for loop_control_var in sequence:
Statement block
● Range() function:
range(beg, end, [step])
#script to check whether a given
#script to find the factorial of a #number is prime or not
# given number n=input('Enter a number: ')
n=input('Enter a number: ') prime=1
fact=1 for i in range(2,n):
for i in range(2,n+1): if (n%i == 0):
fact=fact * i print (str(n)+ ' is not a prime')
print (str(n) + '! = ' +str(fact)) prime=0
break
if(prime!=0):
#Script to display all leap years from 1900-2101 print (str(n)+ ' is a prime')
print ('Leap years from 1900-2101 are: ')
for i in range(1900,2101):
if(i%4==0):
print (i)
break, continue and pass
● Break statement
– Terminates a loop operation
● Continue statement
– Skips to the next iteration
● Pass statement
– We use pass when a statement is required syntactically but no
command or code has to be executed.
– It specifies a null operation or simply No Operation (NOP) statement
#Script to print the calendar of any given year
import calendar
#script to demonstrate pass command y=int(input("Enter the year: "))
for i in "Welcome": print ("\n*******CALENDAR*******")
pass #statement doing nothing cal = calendar.TextCalendar(calendar.SUNDAY)
print ("Pass: ",i) i=1
while i<=12:
cal.prmonth(y, i)
i+=1
Functions
● Function: is a block of organized and reasonable program code, that
performs a single, specific and well-defined task
● Need for functions
– Simplifies the problem solving
– Easy to locate errors and debug
– Understanding, coding and testing multiple separate functions are far easier than
doing the same for one huge function
– All the libraries in Python contain predefined and pretested functions can be directly
used by the programmers
– By dividing the project into multiple modules that can carried out parallel
● Calling function: A function which calls another function
● Called function: A function called by another function
● Function declaration: is a statement that identifies a function with its name,
a list of arguments that it accepts, and the type of data it returns
● Function definition: Consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function
functions(cont.)
● Function block in Pythons starts with the keyword ‘ def’ and the function
name follows with a parenthesis ending with a colon(:)
● Function can accept parameters or arguments. It is optional.
● Syntax:
def function_name(arguments):
statements block

#script to print hello message def add(m,n):


def hello(): return m+n
print "Hell Guys........"
hello() a=input("Enter the 1st number: ")
b=input("Enter the 2nd number: ")
#script to accept two numbers and return the result print ('Sum = '+str(add(a,b)))
def add():
a=input("Enter the 1st number: ")
b=input("Enter the 2nd number: ")
return a+b
sum=add()
print ('Sum = '+str(sum))
functions(cont.)
● Scope and life time
● Local variables and global variables
● Function inside another function can be defined
#script to demonstrate nested functions
def fun1():
print ("I am outer function")
def fun2():
print ("I am in inner function")
print("fun2() called")
print ("fun1() called from main")
fun1()
#script to find the factorial of a given # number using functions
def fact(n):
f=1
for i in range(2,n+1):
f=f*i
return f
pass
n=int(input("\nEnter a number: "))
print (str(n)+'! =' +str(fact(n)))
functions(cont.)
● Default arguments
– A function can be called with fewer number of arguments
– Python allows default arguments #Fibonacci series up to n
#script to demonstrate default arguments def fib(n):
def interest(p,n,r=0.12): a, b = 0, 1
return p*n*r while a < n:
print(a, end=' ')
pass a, b = b, a+b
p=int(input("\nEnter the principal: ")) print()
n=int(input("\nEnter time period: "))
r=float(input("\nEnter rate of interest: ")) fib(1000)
print ('Interest: =' +str(interest(p,n,r)))
print ('Interest with default rate: =' +str(interest(p,n)))
Output:
Enter the principal: 100
Enter time period: 12
Enter rate of interest: 2
Interest: =2400.0
Interest with default rate: =144.0
Lambda Functions or Anonymous Functions
● Are the functions that are not declared as other functions
using the ‘def’ keyword, rather they are created using the
‘lambda’ keyword.
● These are throw-away functions, i.e. they are just needed
where they have been created and can be used anywhere a
function is required.
● This feature was added to Python due to the demand from
LISP programmers
● Syntax:
– lambda arguments: expression

#script to demonstrate lambda functions


sum = lambda x,y: x**2 + y**2
print 'Sum of the squares of 5 and 6 is: ',sum(5,6)
Lambda Functions (cont.)
● Lambda functions have no name
● Lambda functions can take any number of arguments
● Can return just one value in the form of an expression
● Lambda functions definition does not have an explicit return statement
● They are one-line version of a function and hence can’t contain
multiple expressions
● They can not access variables other than those in their parameter list
● They can not access global variables
● We can pass lambda functions as an arguments in other functions
Documentation Strings
● Serve the same purpose as that of comments, used to explain the code
● Created using multi-line string to explain the function
● 1st line should always be short and concise giving the summary
● It should not specify information like the object’s name or type
● It should begin with a capital letter and end with a period
● Triple quotes are used to write the strings
● Docstring can be accessed through the __doc__ attribute of the function
● In case of multiple lines, 2nd line should be blank to separate the summary from
the rest of the description
● The first non-blank line after the documentation string determine the amount of
indentation for the entire document string
● Docstrings are retained through the runtime of the program
def func():
"""This is a sample function.

used to explain the document strings


This function will display "Hello World
message"""
print "Hello World!.........."
print (func.__doc__)
Recursive functions
#script to find the factorial of a given number using recursive functions
def rfact(n):
if(n<=1):
return n;
else:
return n*rfact(n-1)
pass
n=int(input("\nEnter a number: "))
print (str(n)+'! =' +str(rfact(n)))

1.Write a script to find the GCD of given two numbers


2.Write a script to print 1st 100 Fibonacci numbers using recursion
3.Write a script to find the exponent of a number using recursion
(exp(x,y) = 1 if y==0; x*exp(xy-1)
Classes and Objects
● Classes and objects- OOP
● Class: creates a new data type (using ‘class’ keyword)
● Object: is an instance of a class (using class name)
● Class method: same as functions ,but the first argument
named as self.

#script for sample class


#script for sample class
class xyz: #class definition
class xyz: #class definition
var='Welcome to CBIT' ID=1601
ID=1601 def display(self):
print ('Value of ID: '+str(self.val))
obj=xyz() #object creation obj=xyz() #object creation
print ('Value of var is: '+ str(obj.var)) print ('Value of ID: '+str(obj.val))
print ('Value of ID: ' +str(obj.ID)) obj.display() #using method
Classes and Objects(cont.)
● __init__() method:
– is a special function automatically executed when an object of a class is
created
– Useful to initialize the variables of the class object
● Class variable and object variables
#script todemonstrate mutable type attribute
class xyz: #class definition
#script for demonstration of __init__() fuction evens=[]
class xyz: #class definition odds=[]
def __init__(self,arg): def __init__(self, num):
print ('In class ...') self.num=num
if self.num%2==0:
val=arg xyz.evens.append(num)
print ("Value is: "+str(self.val)) else:
xyz.odds.append(num)
obj1=xyz(100) #obj1 is object variable n1=xyz(34) #object n1
Objj2 = xyz(200) n2=xyz(22)
n3=xyz(43)
n4=xyz(45)
n4=xyz(100)
print ('Even numbers: '+str(n1.evens))
print ('Even numbers: '+str(n1.odds))
Public and Private data members
● Public variables:
– are those defined in the class and can be accessed from anywhere (from
inside the class or outside the class) in the program, of course the dot operator
● Private variables:
– are those that are defined in the class with a double underscore
prefix(__)
– Private variables can be accessed only from within the class and from nowhere
outside the class
#script to demonstrate private and public variables
class xyz:
def __init__(self, var1,var2):
self.var1=var1;
self.__var2=var2; #private class variable
def display(self):
print ('From class method, var1: '+str(self.var1))
print ('From class method, var2: '+str(self.__var2))
obj=xyz(20,30)
obj.display()
print ('From main module, var1: '+str(obj.var1))
print ("From main module, var2: "+str(obj.__var2))
Private data methods and class attributes
● Use double underscore before the function name to define a private member
● To call a private method: (objectname._classname_functionname )
● A method in a class can call other methods.
● Built-in class attributes
– .__dict_: gives a directory containing class’s or object’s namespace
– .__doc__: gives the class documentation string if specified. If not specified, returns none.
– .__name__: returns the name of the class
– .__module__.: gives the name of the module in which the class is defined
– .__bases__: used in inheritance to return the base classes in the order of their
occurrence in the basic class list

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

>>>from math import pi >>>from math import sqrt as square_root


>>> print square_root(9)
>>> print ("PI = ",+ pi) 3.0
('PI = ', 3.141592653589793)
Modules (cont.)
#script to add two numbers that are given using command line arguments
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
sum=a+b
print ("Sum = ",sum)
● sys.exit(): used to exit from Python
import sys
Print (“Hello World:)
sys.exit(0)
● Name of Module: We can find the name of the module by using name attribute of the
module #MyModule.py
def display():
print "Hello, Welcome to CBIT"
print "Name of this module is: ",__name__
str =”Welcome to LPSL!!!!”; #variable definition
import MyModule.py
print ("MyModuel str= “, MyModule.str)
MyModule.display()
Print( “Name of this module is: ",__name__)
Making our own modules
● Program that defines a function large in a module which will be used
to find larger of two values and called from code in another module
#MyModule.py
def large(a,b):
#larger.py
If a>b:
import Mymodule
return a
print ("Large(45,90): ",Mymodule.large(50,90))
else:
print ("Large(80,40): ",Mymodule.large(80,40))
return b
print ("Large('a','A'): ",Mymodule.large('a', 'A'))
print ("Large('MGIT','CBIT'): \n",Mymodule.large('MGIT', 'CBIT'))

● dir() function: is a built-in function that lists the defined identifies in a


module
#dir.py >>>import sys >>>import calendar
def print_var(x): >>>dir(sys) >>>print (calendar.month(2018,3)
print(x)
x=100 >>>import __builtin__
print_var(x) >>>print (dir(__builtin__)
print(dir())
Python Modules
● Python module is a file that contains definitions and statements
● When a Python file is executed directly, it is the main module. Main
modules are given the special name __main__ and provides the basis
for a complete program
● Main module may import any number of other modules which may in turn
import other modules
● Main module of a Python program cannot be imported into other modules
● Namespace: is a container that provides a named context for identifiers
– Name spaces enable programs to avoid potential name clashes by associating
each identifier with the namespace from which it originates
#module1 import module1
def repeat_x(x): import module2
return x*2 result=repeat_x(6) #ambiguous reference for identifier repeat_x
#module2 import module1
def repeat_x(x): import module2
return x**2 result1=module1.repeat_x(6) #refer to repeat_x(x) in module1
result2=module2.repeat_x(6) #refer to repeat_x(x) in module1
Python Modules
● Namespace can be
– Built-in (contain all built-in functions, constants, etc.
– Global (contains identifiers of currently executing modules) and
– Local : module private variables
● All the identifiers defined in a module are public by default. i.e. accessible by any
other module that imports
● Private identifier: are those which cannot be accessed by other
modules. This can be done by starting the identifiers with two double underscores
(__)
● When a module is imported using import * from modulename, all the
identifiers of a module’s namespace is imported except the private ones.
● Advantages of Modules:
1. Provides all the benefits of modular software design
2. Modules provide services and functionality that can be reused in other modules
3. Standard library pf Python contain a set of modules
4. It allows us to logically organize the code so that it becomes easier to
understand and use
Packages in Python
● Packages in Python
– Is a hierarchical file directory structure that has modules and
other packages within it.
– Like modules, we can create packages easily
– Every package in Python is a directory which must have a
special file called __init__.py. This file not even have a
single line of code, it is simply added to indicate that
this directory is not an ordinary directory and contains a
Python package
– Packages are imported in to our programs similar t modules
– Example:
● import MyPackage.MyModule or
● From MyPackage import MyModule
Packages in Python(cont.)
● __init__.py is a important file that also determines which modules the
package exports as the API while keeping other modules internal, by
overriding the __all__ variables as shown below:
__init__.py:
__all__=[“MyModule”]
● Key points to remember
– Packages are searched for in the path specified by sys.path
– __init__.py file can be an empty and may also be used to execute initialization code for
the package or set the __all__variable
– The import statement first checks if the item is defined in the package. If it is unable to
find it, an EmportError exception is raised
– When importing an item using syntax like import item.subitem.subitem, each item
except the last must be a package. The last item should be either a module or a
package. In no case it can be a class or function or variable defined in the previous
item
– Packages have an attribute __path__, which is initialized with a list having the name of
the directory holding the __init__.Py. The __path__ attribute can be modified to change
the future searches for modules and sub-packages contained in the package
Packages in Python(cont.)
#program to print absolute values, square #root and cubes of a number
import math
def cube(x):
return x**3

a = -200
print (“a = “,a)
a=abs(a)
print (“abs(a) = “,a)
print (“Cube of 200= “, cube(a))

#program to generate 10 random numbers between 1 to 100


import random

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)

– fileobj.close(): used to close the specified file


– fileobj.read(): used to read data from the file
– fileobj.write(): used to write the data in to the specified file

#srcipt to create a new file and append data to it


file=open("newfile.txt","w")
file.write("Hi Welcome to LPSL, BE 2/4 CSE1.\nThis is a sample text
file created")
file.close()
print "Data written to the file.."
file=open("newfile.txt","a")
file.write("\nThis line added to the current by Prof.Swamy Das\n")
file.close()
read(), readline()
● fileobject.read([count]): used to read a specified number of bytes.
● fileobject.readline():used to read a line
● fileobject.readlines():used to read all the lines
● ist(): used to list the entire file (ex. print(list(fileobj))
● with keyword (with open(“filename”, “r”) as file == file=open(“filename”,”r”)
● Splitting words [ file.split() ]

#srcipt to read from a file #srcipt to read from a file


file=open("file2.py","r") file=open("file2.py","r")
print ("First 20 bytes of the file are: ") print ("\n\nFirst line of the file: ")
print (file.read(40)) print (file.readline())
print ("\n\nRest of the data is: \n") print ("\nSecond line of the fle is:")
print (file.read()) print (file.readline())
file.close() print ("\n\nRest of the lines are:")
print (file.readlines())
#srcipt to read from a file file.close()
with open("file2.py","r") as file:
line =file.readline() Other operations:
words=line.split() fileno(), flush(),
print ("\nWords of the first line are: ") readline(n), truncate(),
print(words) rstrip(), seek(offset, from)
Problems
1.Write a script to calculate the area of a circle?
2.Write a script to find the average of given two numbers. Also print their
deviation?
3.Write a script to calculate the bill amount for an item given its quantity,
value, discount and tax?
4.Write a script to convert degrees Fahrenheit into degrees Celsius? (0.56
*(Fahrenheit-32))
5.Write a script to calculate a student’s result based on two examinations, 1
group discussion and 3 other activities. The weightage activities = 30%,
group discussion=20% and examinations=50%
6.A company decides to give bonus to all its employees on Diwali. A 5%
bonus on salary is given to the male workers and 10% bonus on salary to
the female workers. Write a script to enter salary of the employee and sex
of the employee. If the salary of the employee is less than Rs. 10,000 then
the employee gets additional 2% bonus on salary. Calculate the bonus that
has to be given to the employee and display the total amount that the
employee will get?
Problems (cont.)
7.Write a script that prompts the user to enter a number between 1-7 and then
displays the corresponding day of the week?
8.Write a script to take input from the user and then check whether it is a number or
a character? If it is a character, determine whether it is in uppercase or lowercase?
9.Write a script to calculate root of a quadratic equation?
10.Write a script to enter the marks of a student in 4 subjects. Then calculate the
total and aggregate, and display the grade obtained by the student.if the student
scores an aggregate greater than 75%, then the grade is “DISTINCTION”. If
aggregate is >=60 and <75, then the grade is “FIRST DIVISION”. If aggregate is
>=0 and <60, then the grade is “SECOND DIVISION”. If aggregate is >=40 and
<50, then the grade is “THIRD DIVISION”. Else the grade is “FAIL”.
11.Write a script to find whether a given number is an Armstrong number or not?
(Hint. A number is said to be Armstrong numbers if the sum of the cubes of its
digits is equal to the number itself. Example: 371 is an Armstrong number since
3** + 7**3 + 1**3=371)
12.Write a script to read a character until a ‘*’ is encountered. Also count the number
of uppercase, lowercase and numbers entered by the users
Problems (cont.)
1.Write a script using while loop to read the numbers until -1 is encountered. Also,
count the number of prime numbers and composite numbers entered by the user?
2.Write a script to calculate pow(x,n)?
3.Write a class for student data?
4.Write a class for simple bank operations?
5.Write a simple script to demonstrate the use of modules usage?
6.Write a script to demonstrate of error handling in Python?
7.Write a Python script that takes a number from Qt UI and displays the information
that the given number is prime of not?
8.Write a Python script using PyQt that takes the file name from the user and
displays on to the UI
9.Write a Python script using PyQt that displays takes your name and displays
“Welcome to <Your name> along with your photograph on the UI.
10. Write Python script using PyQt that display a multiple choice question and allows
the user to give his/her answer and then says “You are correct or Wrong”
References
● Reema Thareja “ Pythons Programming using Problem
Solving Approach”, Oxford Press
● Www.python.org

Das könnte Ihnen auch gefallen