Python Full Material
Python Full Material
What is an Algorithm?
An algorithm is a finite line of code developed to be executed in the defined
sequence to solve problems and produce the desired outcomes. An algorithm is
generally written in a common language (pseudo-code) and then implemented in
any programming language. It is recommended to write the pseudo-code of the
algorithm on paper and test using some test cases before the implementation.
NOTATIONS
Flow chart is defined as graphical representation of the logic for
problem solving.
The purpose of flowchart is making the logic of the program clear in a
visual representation.
Rules for drawing a flowchart
The flowchart should be clear, neat and easy to follow.
The flowchart must have a logical start and finish.
Only one flow line should come out from a process symbol.
Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.
Only one flow line is used with a terminal symbol.
1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications.
Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON
Script mode:
In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
Scripts can be saved to disk for future use. Python scripts have the extension
.py, meaning that the filename ends with .py
Save the code with filename.py and run the interpreter in script mode to execute
the script.
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
2.1Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex numbers. They
are defined as,
2.2 Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>> print(s[2]) Accessing the item in the
o position 0
>>> print(s[6]) Accessing the item in the
O position 2
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till
position -1) od morning last.
2.2.2 Lists
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets[ ].
Items in the lists can be of different data types.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
2.2.4Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) Accessing the item in the
python position 0
>>> t[2] Accessing the item in the
101
position 2
Slicing( ending >>>print(t[1:3]) Displaying items from 1st
position -1) (7.79, 101) till 2nd.
Altering the tuple data type leads to error. Following error occurs when user tries to
do.
If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
3.1VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used
later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
3.2KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other
identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
3.3IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore (_).
9 Unit 2: Data ,expressions, Statements
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
3.6 COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
3.7 DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or
method definition. We must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double.__doc__)
Function to double the value
Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator
Types of Operators:
-Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
13 Unit 2: Data ,expressions, Statements
4.1 Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5
Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c + a
Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c =2
c %= a
print("Line 5 - Value of c is ",
c) c **= a
print("Line 6 - Value of c is ",
c) c //= a
print("Line 7 - Value of c is ", c)
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is',a and b) not x is False
print('a or b is',a or b)
print('not a is',not a)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
17 Unit 2: Data ,expressions, Statements
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
18 Unit 2: Data ,expressions, Statements
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
6.1 FUNCTIONS:
Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building
blocks called function.
Need For Function:
When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
as function.
Debugging, Testing and maintenance becomes easy when the program is divided
into subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description
20 Unit 2: Data ,expressions, Statements
>>>max(3,4) # returns largest element
4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>chr(5) #returns a character (a string) from an integer
\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name: ") # reads and returns the given string
enter name : George
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the
flow of execution. This means that you will read the def statements as you are scanning
from top to bottom, but you should skip the statements of the function definition until
you reach a point where that function is called.
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
6.8 ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments: The number of arguments in the function call should
match exactly with the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40
6.9 MODULES:
A module is a file containing Python definitions ,functions, statements and
instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the
module.
ILLUSTRATIVE PROGRAMS
Program for SWAPPING(Exchanging )of Output
values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value ")) Enter b value 8
c=a a=8
a=b b=5
b=c
print("a=",a,"b=",b,)
Part A:
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the example
(i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression and find the result
(a+b)*c/d
a+b*c/d
18. Write a python program to print ‘n’ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Define the scope and lifetime of a variable in python.
27. Point out the uses of default arguments in python
28. Generalize the uses of python module.
29. Demonstrate how a function calls another function. Justify your answer.
30. List the syntax for function call with and without arguments.
31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
33. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.
31
Find greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output
print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)
for i in range(1,5,1): 1 4 9 16
print(i*i)
for i in range(1,5,1): 1 8 27 64
print(i*i*i)
32
Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25
33
factorial of n numbers/product of n numbers Output
i=1 3628800
product=1
while(i<=10):
product=product*i
i=i+1
print(product)
34
check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by
if(n%5==0): 5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()
35
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()
UNIT III
CONTROL FLOW, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass;
Fruitful functions: return values, parameters, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions and methods, string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the
array of numbers, linear search, binary search.
BOOLEAN VALUES:
Boolean:
Boolean data type have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string,
list, tuple, dictionary or not.
To check particular element is available in the list or not.
Operators are in and not in.
Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
CONDITIONALS
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
Flowchart:
alternative (if-else)
In the alternative the condition must be true or false. In this else statement can
be combined with if statement. The else statement contains the block of code that
executes when the condition is false. If the condition is true statements inside the if get
executed otherwise else part gets executed. The alternatives are called branches,
because they are branches in the flow of execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
Chained conditionals(if-elif-else)
The elif is short for else if.
This is used to check more than one condition.
If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according to
the condition.
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
9 Unit 3:control flow, functions
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
positive negative or zero output
n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
ITERATION/CONTROL STATEMENTS:
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition with in
a time is called state.
While loop:
While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression is True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while starts with indentation and the first
unindented line marks the end.
Syntax:
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
It is used when a statement is required syntactically but you don’t want any code
to execute.
It is a null statement, nothing happens when it is executed.
Fruitful Function
Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
19 Unit 3:control flow, functions
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
Parameters are the variables which used in the function definition. Parameters
are inputs to functions. Parameter receives the input from the function call.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with
number of arguments in the function call.
Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the parameter
according to their position. When we call functions in keyword parameter, the order of the
arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")
Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( “kumar”):
student( “ajay”):
In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (“bala”,102,90)
Example: Output:
math.sqrt(math.log(10))
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
Strings:
String is defined as sequence of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment
Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
26 Unit 3:control flow, functions
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace only.
17 a.istitle() >>> a.istitle() checks whether string is title
False cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether string starts
True with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring, if
0 it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
23 max(a) max(a) Return the maximum
>>>’y’ character in the string
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or
variables in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
27 Unit 3:control flow, functions
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)
List as array:
Array:
Array is a collection of similar elements. Elements in the array can be accessed by
index. Index starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
Example
Program to find sum of Output
array elements
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Methods in array
a=[2,3,4,5]
ILLUSTRATIVE PROGRAMS:
Square root using newtons method: Output:
def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loopwith flowchart.
9. Differentiate break and continue.
10. mention the use of pass
11. what is fruitful function
12. what is void function
13. mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.
A list is a sequence of values. In a string, the values are characters but in a list, list values
can be any type.
Elements or Items:
The values in a list are called elements or items. list must be enclosed in square brackets
([and]).
Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
Nested List:
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
Empty List:
A list that contains no elements is called empty list. It can be created with empty
brackets, [].
Assigning List Values to Variables:
Example:
>>>numbers=[40,121]
>>>characters=[‘x’,’y’]
>>>print(numbers,characters)
Output:
[40,12][‘x’,’y’]
4.1.1 LIST OPERATIONS:
Example 1: The + operator concatenates lists:
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>c=a+b
>>>c
Output: [1,2,3,4,5,6]
Example 2:
The * operator repeats a list given number of times:
>>>[0]*4
Output:
[0,0,0,0]
>>>[1,2,3]*3
Output:
[1,2,3,1,2,3,1,2,3]
The first example repeats [0] four times.The second example repeats [1,2,3] three
times.
4.1.2 LIST SLICES:
List slicing is a computationally fast way to methodically access parts of given data.
Syntax:
Listname[start:end:step]where :end represents the first value that is not in the
selected slice. The differencebetween end and start is the numbe of elements selected (if step is
1, the default).The start and end may be a negative number. For negative numbers, the count
starts from the end of the array instead of the beginning.
Example:
>>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
Lists are mutable, so it is useful to make a copy before performing operations that
modify this. A slice operator on the left side of an assignment can update multiple
elements.
Example:
>>>t[1:3]=[‘x’,’y’]
>>>t
Output:
[‘a’,’x’,’y’,’d’,’e’,’f’]
Example 2:
>>>for i in range(len(numbers)):
Numbers[i]=numbers[i]*2
Above example is used for updating values in numbers variables.Above loop traverses
the list and updates each element. Len returns number of elements in the list. Range returns a list
of indices from 0 to n-1, where n is the length of the list.Each time through the loop i gets the
index of next element. A for loop over an empty list never runs the body:
Example:
for x in []:
print(‘This won’t work’)
A list inside another list counts as a single element. The length of the below list is four:
[‘spam’,1,[‘x’,’y’],[1,2,3]]
Example 3:
colors=[“red”,”green”,”blue”,”purple”]
for i in range(len(colors)):
print(colors[i])
Output:
red
green
blue
purple
4.1.5 MUTABILITY:
Lists are mutable. Mutable means, we can change the content without changing the
identity. Mutability is the ability for certain types of data to be changed without entirely
recreating it.Using mutable data types can allow programs to operate quickly and efficiently.
Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
[42,5]
Figure 4.1 shows the state diagram for cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.
numbers contains two elements; the diagram shows that the value of the second element
has been reassigned from 123 to 5. empty refers to a list with no elements.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
4.1.6 ALIASING
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
Example 2:
>>> t2
Output:
None
4.2. TUPLES
A tuple is a sequence of values.
The values can be any type and are indexed by integers, unlike lists.
Tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, we have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
Output:
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
Output:
<class 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates
an empty tuple.
Example:
>>> t = tuple()
>>> t
Output: ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements
of the sequence:
Example:
>>> t = tuple('lupins')
>>> t
Output: ('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, we should avoid using it as a variable
name. Most list operators also work on tuples. The bracket operator indexes an element:
Example:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
Output: 'a' And the slice operator selects a range of elements.
Example:
>>> t[1:3] Output:('b', 'c')But if we try to modify one of the elements of the
tuple, we get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignmentBecause tuples are immutable, we
can’t modify the elements. But we can replace one
tuple with another: Example:
>>> t = ('A',) + t[1:]
>>> t
Output:
('A', 'b', 'c', 'd', 'e')This statement makes a new tuple and then makes t refer to it.
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
Example 1:
>>> (0, 1, 2) < (0, 3, 4)
Output:
True
Example 2:
>>> (0, 1, 2000000) < (0, 3, 4)
Output:
True
4.2.1 TUPLE ASSIGNMENT
It is often useful to swap the values of two variables. With conventional assignments, we
have to use a temporary variable. For example, to swap a and b:
Example:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated before any
of the assignments.The number of variables on the left and the number of values on the right
have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, we could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname
'monty'
>>> domain
'python.org'
4.2.2 TUPLE AS RETURN VALUES
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time. The built-in function divmod takes two arguments and returns a
tuple of two values, the quotient and remainder. We can store the result as a tuple:
Example:
>>> t = divmod(7, 3)
>>> t
Ouput:
(2, 1)
Or use tuple assignment to store the elements separately:
Example:
>>> quot, rem = divmod(7, 3)
>>> quot
Output:
2
Example:
>>> rem
Output:
1
Here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.
4.3 DICTIONARIES
Dictionaries have a method called items that returns a sequence of tuples, where each
tuple is a key-value pair.
4.3.1 OPERATIONS AND METHODS
Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])
The result is a dict_items object, which is an iterator that iterates the key-value pairs. We
can use it in a for loop like this:
Example:
>>> for key, value in d.items():
... print(key, value)
Output:
c2
a0
b1
As we should expect from a dictionary, the items are in no particular order.
Going in the other direction, we can use a list of tuples to initialize a new dictionary:
Example:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way to create a dictionary:
Example:
>>> d = dict(zip('abc', range(3)))
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. It is common to use tuples as keys in dictionaries (primarily
because we can’t use lists). For example, a telephone directory might map from last-name, first-
name pairs to telephone numbers. Assuming that we have defined last, first and number, we
could write: directory [last, first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary. For last, first in directory:
print(first, last, directory[last,first])
This loop traverses the keys in directory, which are tuples. It assigns the elements of each
tuple to last and first, then prints the name and corresponding telephone number.
There are two ways to represent tuples in a state diagram. The more detailed version
shows the indices and elements just as they appear in a list. For example, the tuple('Cleese',
'John') would appear as in Figure 4.4. But in a larger diagram we might want to leave out the
details. For example, a diagram of the telephone directory might appear as in Figure 4.5.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone
number in the diagram is the complaints line for the BBC, so please don’t call it.
ALGORITHM:
1. Compare the current element in the iteration (say A) with the previous adjacent element
to it. If it is in order then continue the iteration else, go to step 2.
2. Swap the two elements (the current element in the iteration (A) and the previous adjacent
element to it).
3. Compare A with its new previous adjacent element. If they are not in order, then proceed
to step 4.
4. Swap if they are not in order and repeat steps 3 and 4.
5. Continue the iteration.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.3 MERGE SORT
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used for
merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C
implementation for details.
The following diagram shows the complete merge sort process for an example array {38,
27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is
recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge
processes comes into action and starts merging arrays back till the complete array is merged.
ALGORITHM:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
PROGRAM:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
n = input("Enter the size of the list: ")
n=int(n);
alist = []
for i in range(n):
alist.append(input("Enter %dth element: "%i))
mergeSort(alist)
print(alist)
Input:
a = [16, 19, 11, 15, 10, 12, 14]
Output:
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.5 HISTOGRAM
A histogram is a visual representation of the Distribution of a Quantitative variable.
Appearance is similar to a vertical bar graph, but used mainly for continuous
distribution
It approximates the distribution of variable being studied
A visual representation that gives a discretized display of value counts.
Example:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
The name of the function is histogram, which is a statistical term for a collection of
counters (or frequencies).
The first line of the function creates an empty dictionary. The for loop traverses the
string.Each time through the loop, if the character c is not in the dictionary, we create a new item
with key c and the initial value 1 (since we have seen this letter once). If c is already in the
dictionary we increment d[c]. Here’s how it works:
Example:
>>> h = histogram('brontosaurus')
>>> h
Output:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters 'a' and 'b' appear once; 'o' appears twice, and so
on. Dictionaries have a method called get that takes a key and a default value. If the key appears
in the dictionary, get returns the corresponding value; otherwise it returns the default value. For
example:
>>> h = histogram('a')
>>> h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
As an exercise, use get to write histogram more concisely. We should be able to eliminate
the if statement.
If we use a dictionary in a for statement, it traverses the keys of the dictionary. For
example, print_hist prints each key and the corresponding value:
def print_hist(h):
for c in h:
print(c, h[c])
Here’s what the output looks like:
>>> h = histogram('parrot')
>>> print_hist(h)
a1
p1
r2
t1
o1
Again, the keys are in no particular order. To traverse the keys in sorted order, we can use
the built-in function sorted:
>>> for key in sorted(h):
... print(key, h[key])
a1
o1
p1
r2
t1
Write a function named choose_from_hist that takes a histogram as defined in Histogram
given above and returns a random value from the histogram, chosen with probability in
proportion to frequency. For example, for this histogram:
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t)
>>> hist
{'a': 2, 'b': 1}
The function should return 'a' with probability 2/3 and 'b' with probability 1/3.
TWO MARKS
1. What are elements in a list? Give example.
The values in a list are called elements or items.
A list must be enclosed in square brackets ([and]).
Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
2. What is a nested list? Give example.
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
3. What is a empty list?
A list that contains no elements is called empty list. It can be created with empty
brackets, [].
UNIT – V
FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments,
errors
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math
module),
Explore packages.
Files, Exceptions, Modules, Packages:
Files and exception:
A file is some information or data which stays in the computer storage devices.
Python gives
you easy ways to manipulate these files. Generally files divide in two categories,
text file and binary file. Text files are simple text where as the binary files contain
binary
data which is only readable by computer.
Text files: In this type of file, Each line of text is terminated with a special
character
called EOL (End of Line), which is the new line character („\n‟) in python by
default.
Binary files: In this type of file, there is no terminator for a line and the data is
stored
after converting it into machine understandable binary language.
An exception is an event, which occurs during the execution of a program that
disrupts the
normal flow of the program's instructions. In general, when a Python script
encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python
object
that represents an error.
Text files:
We can create the text files by using the syntax:
Variable name=open (“file.txt”, file mode)
For ex: f= open ("hello.txt","w+")
We declared the variable f to open a file named hello.txt. Open takes 2
arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
Here we used "w" letter in our argument, which indicates write and the plus sign
that
means it will create a file if it does not exist in library
104
The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it
File Modes in Python:
Mode Description
'r'
This is the default mode. It Opens file for reading.
'w'
This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x'
Creates a new file. If file already exists, the operation fails.
'a'
Open file in append mode.
If file does not exist, it creates a new file.
't'
This is the default mode. It opens in text mode.
'b'
This opens in binary mode.
'+'
This will open a file for reading and writing (updating)
Reading and Writing files:
The following image shows how to create and open a text file in notepad from
command
prompt
105
(or)
Hit on enter then it shows the following whether to open or not?
Click on “yes” to open else “no” to cancel
# Write a python program to open and read a file
a=open(“one.txt”,”r”)
print(a.read())
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
106
a.close()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/filess/f1.py
welcome to
(or)
Note: All the program files and text files need to saved together in a particular
file then
only the program performs the operations in the given file mode
f.close() ---- This will close the instance of the file somefile.txt stored
# Write a python program to open and write “hello world” into a file?
f=open("1.txt","a")
f.write("hello world")
f.close()
Output:
107
(or)
Note: In the above program the 1.txt file is created automatically and adds
hello world
into txt file
If we keep on executing the same program for more than one time then it append
the data
that many times
# Write a python program to write the content “hi ” for the
existing file.
f=open("1.txt",'w')
f.write("hi ")
f.close()
Output:
In the above program the hello txt file consist of data like
108
But when we try to write some data on to the same file it overwrites and saves with
the
current data (check output)
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
# Write a python program to open and write the content to file and read it.
fo=open("abc.txt","w+")
fo.write(" ")
print(fo.read())
fo.close()
Output:
(or)
Note: It creates the abc.txt file automatically and writes the data into it
109
Command line arguments:
The command line arguments must be given whenever we want to give the input
before the
start of the script, while on the other hand, raw_input() is used to get the input
while the
python program / script is running.
The command line arguments in python can be processed by using either „sys‟
module,
„argparse‟ module and „getopt‟ module.
„sys‟ module :
Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line
arguments as
String.
sys.argv is the list of commandline arguments passed to the Python program. argv
represents
all the items that come along via the command line input, it's basically an array
holding the
command line arguments of our program
>>> sys.modules.keys() -- this prints so many dict elements in the form of list.
# Python code to demonstrate the use of 'sys' module for command line arguments
import sys
# command line arguments are stored in the form
# of list in sys.argv
argumentList = sys.argv
print(argumentList)
# Print the name of file
print(sys.argv[0])
# Print the first argument after the name of file
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
#print(sys.argv[1])
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/cmndlinarg.py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
110
Note: Since my list consist of only one element at „0‟ index so it prints only that
list
element, if we try to access at index position „1‟ then it shows the error like,
IndexError: list index out of range
------------------
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py
# write a python program to get python version.
import sys
print("System version is:")
print(sys.version)
print("Version Information is:")
print(sys.version_info)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =
System version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
„argparse‟ module :
Python getopt module is very similar in working as the C getopt() function for
parsing
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
111
import argparse
parser = argparse.ArgumentParser()
print(parser.parse_args())
„getopt‟ module :
Python argparse module is the preferred way to parse command line arguments. It
provides a
lot of option such as positional arguments, default value for arguments, help
message,
specifying data type of argument etc
It parses the command line options and parameter list. The signature of this
function is
mentioned below:
getopt.getopt(args, shortopts, longopts=[ ])
args are the arguments to be passed.
shortopts is the options this script accepts.
Optional parameter, longopts is the list of String parameters this function accepts
which should be supported. Note that the -- should not be prepended with option
names.
-h --------- print help and usage message
-m --------- accept custom option value
-d --------- run the script in debug mode
import getopt
import sys
argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
112
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py ==
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py']
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions
when it
encounters errors. When writing a program, we, more often than not, will
encounter errors. Error caused by not following the proper structure (syntax) of the
language
is called syntax error or parsing error
ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division
(or
modulo) operation was zero.
OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the
limits of
the current Python runtime. This is typically due to excessively large float values,
as integer
values that are too big will opt to raise memory errors instead.
ImportError:
It is raised when you try to import a module which does not exist. This may happen
if you
made a typing mistake in the module name or the module doesn't exist in its
standard path.
In the example below, a module named "non_existing_module" is being imported
but it
doesn't exist, hence an import error exception is raised.
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range.
In the
example below, the list abc contains only 3 entries, but the 4th index is being
accessed,
which will result an IndexError exception.
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In
example
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
below, an int and a string is added, which will result in TypeError exception.
113
IndentationError:
Unexpected indent. As mentioned in the "expected an indentedblock" section,
Python not
only insists on indentation, it insists on consistentindentation. You are free to
choose the
number of spaces of indentation to use, but you then need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable
to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost
never a
way to successfully execute a piece of code containing syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying, but runs
into
trouble when following your instructions.
Key Error :
Python raises a KeyError whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary.
Value Error:
In Python, a value is the information that is stored within a certain object. To
encounter a
ValueError in Python means that is a problem with the content of the object you
tried to
assign the value to.
Python has many built-in exceptions which forces your program to output an
error when
something in it goes wrong. In Python, users can define such exceptions by
creating a new
class. This exception class has to be derived, either directly or indirectly,
from Exception class.
Different types of exceptions:
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
InterruptedException.
NoSuchFieldException.
NoSuchMethodException
114
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an
incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files.
Hence,
the exceptions should be properly handled so that an abrupt termination of the
program is
prevented.
Python uses try and except keywords to handle exceptions. Both keywords are
followed by
indented blocks.
Syntax:
try :
#statements in try block
except :
#executed when error in try block
Typically we see, most of the times
Syntactical errors (wrong spelling, colon ( : ) missing ….),
At developer level and compile level it gives errors.
Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may obtained.
Run time error (In this case, if the user doesn‟t know to give input, 5/6 is ok but
if
the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by the
system, it is (mistake) done by the user.
The things we need to observe are:
1. You should be able to understand the mistakes; the error might be done by user,
DB
connection or server.
2. Whenever there is an error execution should not stop.
Ex: Banking Transaction
3. The aim is execution should not stop even though an error occurs.
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
115
For ex:
a=5
b=2
print(a/b)
print("Bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py
2.5
Bye
The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below
a=5
b=0
print(a/b)
print("bye") #this has to be printed, but abnormal termination
Output:
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/ex2.py", line
3, in <module>
print(a/b)
ZeroDivisionError: division by zero
To overcome this we handle exceptions using except keyword
a=5
b=0
116
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex3.py
number can not be divided by zero
bye
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
The except block executes only when try block has an error, check it below
a=5
b=2
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py
2.5
For example if you want to print the message like what is an error in a
program
then we use “e” which is the representation or object of an exception.
a=5
b=0
try:
117
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
number can not be divided by zero division by zero
bye
(Type of error)
Let us see some more examples:
I don‟t want to print bye but I want to close the file whenever it is opened.
a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
Output:
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex6.py
resource opened
2.5
resource closed
118
Note: the file is opened and closed well, but see by changing the value of b to
0,
a=5
b=0
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex7.py
resource opened
number can not be divided by zero division by zero
Note: resource not closed
To overcome this, keep print(“resource closed”) in except block, see it
a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
119
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex8.py
resource opened
number can not be divided by zero division by zero
resource closed
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
The result is fine that the file is opened and closed, but again change the
value of
b to back (i.e., value 2 or other than zero)
a=5
b=2
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5
But again the same problem file/resource is not closed
To overcome this python has a feature called finally:
This block gets executed though we get an error or not
Note: Except block executes, only when try block has an error, but finally
block
executes, even though you get an exception.
a=5
b=0
try:
120
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
the value can not be divided by zero division by zero
resource closed
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
change the value of b to 2 for above program, you see the output like
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number 6
6
resource closed
Instead give input as some character or string for above program, check the
output
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number p
resource closed
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/ex10.py", line
7, in <module>
k=int(input("enter a number"))
ValueError: invalid literal for int() with base 10: ' p'
121
#--------------------
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong...",e)
finally:
print("resource closed")
Output:
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex11.py
resource open
the value can not be divided by zero division by zero
resource closed
Change the value of b to 2 and give the input as some character or string
(other
than int)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex12.py
resource open
2.5
enter a number p
invalid input
resource closed
Modules (Date, Time, os, calendar, math):
• Modules refer to a file containing Python statements and definitions.
122
• We use modules to break down large programs into small manageable and
organized
files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of
copying
their definitions into different programs.
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules.
Advantages :
• Simplicity: Rather than focusing on the entire problem at hand, a module
typically
focuses on one relatively small portion of the problem. If you‟re working on a
single
module, you‟ll have a smaller problem domain to wrap your head around. This
makes
development easier and less error-prone.
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a way
that
minimizes interdependency, there is decreased likelihood that modifications to a
single module will have an impact on other parts of the program. This makes it
more
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
123
Here, we have defined a function add() inside a module named example. The
function takes
in two numbers and returns their sum.
How to import the module is:
• We can import the definitions inside a module to another module or the
Interactive
interpreter in Python.
• We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.
• Using the module name we can access the function using dot (.) operation. For
Eg:
>>> import example
>>> example.add(5,5)
10
• Python has a ton of standard modules available. Standard modules can be
imported
the same way as we import our user-defined modules.
Reloading a module:
def hi(a,b):
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
print(a+b)
hi(4,4)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/add.py
8
>>> import add
8
124
>>> import add
>>> import add
>>>
Python provides a neat way of doing this. We can use the reload() function inside
the imp module to reload a module. This is how its done.
• >>> import imp
• >>> import my_module
• This code got executed >>> import my_module >>> imp.reload(my_module)
This
code got executed <module 'my_module' from '.\\my_module.py'>how its done.
>>> import imp
>>> import add
>>> imp.reload(add)
8
<module 'add' from
'C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy\\add.py'>
The dir() built-in function
>>> import example
>>> dir(example)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__',
'__spec__', 'add']
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '__warningregistry__', 'add', 'example', 'hi', 'imp']
It shows all built-in and user-defined modules.
For ex:
125
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
>>> example.__name__
'example'
Datetime module:
# Write a python program to display date, time
>>> import datetime
>>> a=datetime.datetime(2019,5,27,6,35,40)
>>> a
datetime.datetime(2019, 5, 27, 6, 35, 40)
# write a python program to display date
import datetime
a=datetime.date(2000,9,18)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2000-09-18
# write a python program to display time
import datetime
a=datetime.time(5,3)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
05:03:00
#write a python program to print date, time for today and now.
import datetime
126
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29 12:49:52.235581
2019-11-29 12:49:52.235581
#write a python program to add some days to your present date and print the
date
added.
import datetime
a=datetime.date.today()
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
b=datetime.timedelta(days=7)
print(a+b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-12-06
#write a python program to print the no. of days to write to reach your
birthday
import datetime
a=datetime.date.today()
b=datetime.date(2020,5,27)
c=b-a
print(c)
Output:
127
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
180 days, 0:00:00
#write an python program to print date, time using date and time functions
import datetime
t=datetime.datetime.today()
print(t.date())
print(t.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29
12:53:39.226763
Time module:
#write a python program to display time.
import time
print(time.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
1575012547.1584706
#write a python program to get structure of time stamp.
import time
print(time.localtime(time.time()))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
128
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13,
tm_min=1,
tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)
#write a python program to make a time stamp.
import time
a=(1999,5,27,7,20,15,1,27,0)
print(time.mktime(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
927769815.0
#write a python program using sleep().
import time
time.sleep(6) #prints after 6 seconds
print("Python Lab")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
Python Lab (#prints after 6 seconds)
os module:
>>> import os
>>> os.name
'nt'
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> os.mkdir("temp1")
129
Note: temp1 dir is created
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> open("t1.py","a")
<_io.TextIOWrapper name='t1.py' mode='a' encoding='cp1252'>
>>> os.access("t1.py",os.F_OK)
True
>>> os.access("t1.py",os.W_OK)
True
>>> os.rename("t1.py","t3.py")
>>> os.access("t1.py",os.F_OK)
False
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
>>> os.access("t3.py",os.F_OK)
True
>>> os.rmdir('temp1')
(or)
os.rmdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/temp1')
130
Note: Temp1dir is removed
>>> os.remove("t3.py")
Note: We can check with the following cmd whether removed or not
>>> os.access("t3.py",os.F_OK)
False
>>> os.listdir()
['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py',
'br.py',
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py',
'cmndlinarg.py',
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py',
'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py',
'ifelse.py',
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py',
'lis.py',
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py', 'paraarg.py',
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py',
'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py',
'strr3.py',
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py', 'wh4.py', 'wh5.py',
'__pycache__']
>>> os.listdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32')
['argpar.py', 'br.py', 'bu.py', 'cmndlinarg.py', 'DLLs', 'Doc', 'f1.py', 'f1.txt', 'filess',
'functupretval.py', 'funturet.py', 'gtopt.py', 'include', 'Lib', 'libs', 'LICENSE.txt',
'lisparam.py',
'mysite', 'NEWS.txt', 'niru', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe',
'pyyy',
'Scripts', 'srp.py', 'sy.py', 'symod.py', 'tcl', 'the_weather', 'Tools', 'tupretval.py',
'vcruntime140.dll']
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
Calendar module:
131
#write a python program to display a particular month of a year using
calendar
module.
import calendar
print(calendar.month(2020,1))
Output:
# write a python program to check whether the given year is leap or not.
import calendar
print(calendar.isleap(2021))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cl1.py
False
#write a python program to print all the months of given year.
import calendar
print(calendar.calendar(2020,1,1,1))
Output:
132
math module:
# write a python program which accepts the radius of a circle from user and
computes
the area.
import math
r=int(input("Enter radius:"))
area=math.pi*r*r
print("Area of circle is:",area)
Output:
133
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m.py =
Enter radius:4
Area of circle is: 50.26548245743669
>>> import math
>>> print("The value of pi is", math.pi)
O/P: The value of pi is 3.141592653589793
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
134
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
Import all names:
• We can import all names(definitions) from a module using the following
construct.
>>>from math import *
>>>print("The value of pi is", pi)
• We imported all the definitions from the math module. This makes all names
except
those beginnig with an underscore, visible in our scope.
Explore packages:
• We don't usually store all of our files in our computer in the same location. We
use a
well-organized hierarchy of directories for easier access.
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
• Similar files are kept in the same directory, for example, we may keep all the
songs in
the "music" directory. Analogous to this, Python has packages for directories
and modules for files.
• As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptually clear.
• Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules.
• A directory must contain a file named __init__.py in order for Python to consider
it as
a package. This file can be left empty but we generally place the initialization code
for
that package in this file.
• Here is an example. Suppose we are developing a game, one possible
organization of
packages and modules could be as shown in the figure below.
135
• If a file named __init__.py is present in a package directory, it is invoked when
the
package or a module in the package is imported. This can be used for execution of
package initialization code, such as initialization of package-level data.
• For example __init__.py
• A module in the package can access the global by importing it in turn
• We can import modules from packages using the dot (.) operator.
• For example, if want to import the start module in the above example, it is done
as
follows.
• import Game.Level.start
• Now if this module contains a function named select_difficulty(), we must use
the
full name to reference it.
• Game.Level.start.select_difficulty(2)
136
• If this construct seems lengthy, we can import the module without the package
prefix
as follows.
• from Game.Level import start
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
137
<function read at 0x03BD1070>
>>> read()
Department
>>> from IIYEAR.CSE.student import write
>>> write()
Student
# Write a program to create and import module?
def add(a=4,b=6):
c=a+b
return c
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-
32\IIYEAR\modu1.py
>>> from IIYEAR import modu1
Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140
>>> modu1.add()
10
# Write a program to create and rename the existing module.
def a():
print("hello world")
a()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/IIYEAR/exam.py
hello world
>>> import exam as ex
hello world
Downloaded by SK (mspanther1991@gmail.com)