Professional Documents
Culture Documents
Ge3151 PSPP Study Material
Ge3151 PSPP Study Material
Ge3151 PSPP Study Material
PROBLEM SOLVING
Statements:
State:
Transition from one process to another process under specified condition
with in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called
control flow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration
Sequence:
All the instructions are executed one after another is called sequence
execution.
Example:
Selection:
A selection statement causes the program control to be transferred to a
specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Iteration:
In some programs, certain set of statements are executed again and again
based upon conditional test. i.e. executed more than one time. This type of
execution is called looping or iteration.
Example
Functions:
Example:
FLOW CHART
4. Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.
Advantages of flowchart:
Advantages:
Disadvantages:
Example:
PROGRAMMING LANGUAGE
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and
1’s. In machine language the different instructions are formed by taking
different combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands.
For executing any program written in any programming language, the
conversion to machine language is necessary. The program written in
machine language can be executed directly on computer. In this case any
conversion process is not required.
High speed
The machine language program is translation free. Since the conversion
time is saved, the execution of machine language program is extremely fast.
Disadvantage:
➢ It is hard to find errors in a program written in the machine language.
➢ Writhing program in machine language is a time consuming process.
Assembly language:
To overcome the issues in programming language and make the
programming process easier, an assembly language is developed which is
logically equivalent to machine language but it is easier for people to read,
write and understand.
➢ Assembly language is symbolic representation of machine language.
Assembly languages are symbolic programming language that uses
symbolic notation to represent machine language instructions. They are
called low level language because they are so closely related to the
machines.
Assembler
Assembler is the program which translates assembly language instruction
in to a machine language.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine
depends on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
➢ Execution time of assembly language program is more than machine
language program.
➢ Because assembler is needed to convert from assembly language to
machine language.
High level language contains English words and symbols. The specified
rules are to be followed while writing program in high level language. The
interpreter or compilers are used for converting these programs in to
machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are
called interpreter or compiler.
Scripting language:
Markup languages:
Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it uses.
2. simplicity.
❖ An algorithm should be precisely defined and investigated with
mathematical expressions.
❖ Simpler algorithms are easier to understand and easier to program.
❖ Simple algorithms usually contain fewer bugs.
Coding an Algorithm
❖ Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an
opportunity.
❖ A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based on
timing the program on several inputs and then analysing the results
obtained.
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:
1. iterations
2. Recursions
1. Iterations:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop
Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop
Step 1: Start
Step 2: get P, n, r value
Step3:Calculate
SI=(p*n*r)/100
Step 4: Display S
Step 5: Stop
To check greatest of two numbers
Step 1: Start
Step 2: get a,b value
Step 3: check if(a>b) print a is greater
Step 4: else b is greater
Step 5: Stop
To check leap year or not
Step 1: Start
Step 2: get y
Step 3: if(y%4==0) print leap year
Step 4: else print not leap year
Step 5: Stop
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
To check odd or even number
Step 1: Start
Step 2: get num
Step 3: check if(num%2==0) print num is even
Step 4: else num is odd
Step 5: Stop
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop
Step 1: start
step 2: get n value
step 3: set initial value i=1
step 4: check if(i<=n) goto step 5 else goto step 8
step 5: print i value
step 6: increment i value by 2
step 7: goto step 4
step 8: stop
Step 1: start
step 2: get n value
step 3: set initial value i=1, sum=0
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate sum=sum+i
step 6: increment i value by 1
step 7: goto step 4
step 8: print sum value
step 9: stop
Step 1: start
step 2: get n value
step 3: set initial value i=1, fact=1
Step 4: check i value if(i<=n) goto step 5 else goto step8
step 5: calculate fact=fact*i
step 6: increment i value by 1
step 7: goto step 4
step 8: print fact value
step 9: stop
1. What is an algorithm?
Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task. It is an English-like representation of the
logic which is used to solve the problem. It is a step- by-step procedure for
solving a task or a problem. The steps must be ordered, unambiguous and finite
in number.
7. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task.
Functions usually "take in" data, process it, and "return" a result. Once a
function is written, it can be used over and over and over again. Functions can
be "called" from the inside of other functions.
8. Write the pseudo code to calculate the sum and product displaying the
answer on the monitor screen.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2 sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
9. Give the rules for writing Pseudo codes.
• Write one statement per line.
• Capitalize initial keywords.
• Indent to show hierarchy.
• End multiline structure.
• Keep statements to be language independent.
What is computing ?
It is any type of calculation that includes both mathematical and non- arithmetical
steps and follows a well defined model.
Processor
Data -------> Convert or compute -------> information
1) What are the factors used to judge the qualities of the algorithm?
1. Less time
2. Less memory
3. Higher accuracy
4. Sequence
5.Generability
Pseudcode:
procedure HANOI (disk, source,dest,aux)
If disk==0,
move disk from source to dest
ELSE
HANOI (disk-1,source,aux,dest)
MOVE disk from source to dest
HANOI (disk-1,aux,dest,source)
END -IF
END procedure
Flowchart:
Procedure to solve Tower of Hanoi
The goal of the puzzle is to move all the disks from leftmost peg to rightmost
peg.
1. Move only one disk at a time.
2. A larger disk may not be p1aced on top of a smaller disk. For example,
consider n=3 disks
4. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then
Print Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop
INTRODUCTION TO PYTHON:
Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.
Python Features:
Python interpreter:
1. Interactive mode
2. Script mode
1. Interactive mode:
2. Script mode:
❖ Save the code with filename.py and run the interpreter in script mode
to execute the script.
Features of IDLE:
Multi-window text editor with syntax highlighting.
❖ Auto completion with smart indentation.
Python shell to display output with syntax highlightin
Features of IDLE:
Multi-window text editor with syntax highlighting.
❖ Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
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:
Numbers:
Sequence:
1. Strings
➢ A String in Python consists of a series or sequence of characters -
letters, numbers, and special characters.
➢ Strings are marked by quotes:
• single quotes (' ') Eg, 'This a string in single quotes'
• double quotes (" ") Eg, "'This a string in double quotes'"
• triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
lines and sentences."""
➢ Individual character in a string is accessed using a subscript (index).
➢ Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after
it is created.
Indexing:
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
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
3. Tuple:
Basic Operations:
Altering the tuple data type leads to error. Following error occurs when
user tries to do.
Mapping
Dictionaries:
ARIABLES:
KEYWORDS:
IDENTIFIERS:
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 (_).
❖ 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
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
-A value all by itself is considered an expression, and also a variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend
COMMENTS:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
DOCSTRING:
Syntax:
functionname__doc.__
TUPLE ASSIGNMENT
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
Arithmetic operators:
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
Output
x and y is False
x or y is True
not x is False
Bitwise Operators:
Membership Operators:
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators
They are used to check if two values (or variables) are located on the same
part of the memory.
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output
False
True
OPERATOR PRECEDENCE:
❖ Operators with the same precedence are evaluated from left to right
(except exponentiation).
Example:
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15
find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1
a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0
a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1
a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15
ILLUSTRATIVE PROGRAMS
Program for SWAPPING (Exchanging )of values
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c=a
a=b
b=c
print("a=",a,"b=",b,)
Output
Enter a value 5
Enter b value 8
a=8
b=5
Output
enter x1 7
enter y1 6
enter x2 5
enter y2 7
2.5
Program to circulate n numbers
a=list(input("enter the list"))
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])
Output:
enter the list '1234'
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']
1) Boolean:
1. Boolean data type have two values.They are 0 and 1.
2. 0 represents False.
3. 1 represents True.
4. True and False are keywords.
5. Boolean values respond to logical operators (and / or)
Example:
>>>3==5
False
>>>6==6
True
>>>True+True
2
>>>False+True
1
2) CONDITIONALS:
• Conditional if
• Alternative if…..else
• Chained if…elif….else
• Nested if…..else
✓ Conditional if :
1) The if statement is a decision making statement.
2) The conditional if is used to test a condition.
3) Conditional if is used to test a condition.If the condition is
true the statements inside if will be executed.
Syntax:
if (Condition):
statement 1
Flow chart :
Example program:
Output:
Enter the marks:98
The student is pass
✓ Alternative if…..else :
• It is a two way decision making statement.
• In the alternative the condition must be true or false.
• In this else statement can be combined with the 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 get executed.
Syntax:
if (condition 1):
statement 1
else:
statement 2
Flow chart :
Example programs:
Output:
#Program to find odd or even
n=int(input(“Enter the number:”)) Enter the number:5
if (n%2==0): odd number
print(“even number”)
else:
print(“odd number”)
else:
print(“not leap year”)
#Program to find eligible to vote or not Output:
age=int(input(“Enter your age:”)) Enter your age:26
✓ Chained if…..elif…else :
• The elif is short for else if.
• This is used to check more than one condition.
• If the condition 1 is false, it checks the condition 2 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.
• The if can have only one else block, but it can have
multiple elif blocks.
Syntax :
if (condition 1):
statement 1
elif (condition 2):
statement 2
Flow chart :
Example programs :
✓ NESTED CONDITIONALS :
One conditional can also be nested within another.Any number
of condition can be nested inside one another.In this, if condition is
true it checks another if condition 1.If both the conditions are true
statement 1 get executed otherwise statement 2 get executed. If the
condition is false statement 3 get executed.
Syntax:
if (condition):
if (condition 1):
statement 1
else:
statement 2
else:
statement 3
Flow chart:
Example programs :
Output :
Enter n value:-9
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 :
Syntax :
Initial value
While(condition):
Body of while loop
Increement
Flowchart :
Example programs :
#sum of n numbers
n=int(input(“Enter n value:”)) Output :
i=1 Enter n value :10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
#Factorial of n numbers
n=int(input(“Enter n value:”)) Output :
i=1 Enter n value: 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)
#Palindrome or not
n=int(input(“Enter n value:”)) Output :
org=n Enter n value :121
sum=0 The given number is
palindrome
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print(“the given number is palindrome”)
else:
print(“the given number is not palindrome”)
FOR LOOP :
for in range( )
Syntax :
for i range(start,stop,steps):
body of for loop
Flowchart :
for in sequence :
• The for loop in python is 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.
Syntax :
for i in sequence:
print(i)
Example programs :
Output :
Enter n value: 30
5
15
25
#Fibonacci series
a=0
b=1
n=int(input(“Enter the no.of terms:”))
print(“Fibonacci series:”)
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output :
Enter the no. of terms :6
Fibonacci series:
01
1
2
3
5
8
Output :
Enter n value : 10
1
2
5
10
n=int(input(“Enter n value:”))
for i in range (2,n):
if(n%i==0):
print(“The number is not a prime”)
break
else:
print(“The number is a prime number”)
Output :
Enter n value: 7
The number is a prime number
Output :
Enter no.of prime numbers to be displayed:5
2
3
5
7
11
BREAK:
• Break statements can alter the flow of a loop.
• It terminates the current.
• Loop and executes the remaining statement outside the loop.
• If the loop has else statement,that will also gets terminated and
come out of the loop completely.
Syntax :
While(test expression):
If(condition for break):
Break
Flowchart :
Example program :
for i in “welcome”: Output :
if(i==”c”): w
break e
print(i) l
CONTINUE STATEMENT :
It terminates the current iteration and transfer the control to the
next iteration in the loop.
Syntax :
While(test expression):
If(condition for continue):
Continue
Flowchart :
Example program :
for i in “welcome”: Output :
if(i==”c”): w
continue e
print(i) l
o
m
e
PASS STATEMENT :
• 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.
Syntax:
Pass
Break
Example program : Output :
for i in “welcome”: w
if(i==”c”): e
pass l
print(i) c
o
m
e
Differences between BREAK and CONTINUE :
break Continue
• Syntax : • Syntax :
Break Continue
Functions :
• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion
1. 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)
2. VOID FUNCTION :
A function that performs action but don’t returns any
value.
Example :
Print(“Hello”)
Example :
def add():
a=10
b=20
c=a+b
print(c)
add()
3. 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
4. PARAMETERS/ARGUMENTS :
• Parameters are the variables which is used in the function
definition.
• parameters are inputs to function.
• Parameters receives the input from the function call.
• It is possible to define more than one parameter in the function
definition.
TYPES OF PARAMETERS/ARGUMENTS :
a. Required/positional parameters
b. Keyword parameters
c. Default parametrs
d. Variable length parameters
a. Required/positional parameters :
The number of parameter in the function definition should
match with number of arguments in the function call.
Example :
def student(roll,name):
print(roll,name)
student(98 ,”john”)
Output :
98 john
b. Keyword parameters :
When we call a function with some values these values get
assigned to
the parameter according to that position. But when we call a function
in keyword parameter , the order of the arguments can be changed.
Example :
def student(name,roll,mark):
print (name,roll,mark)
student (90.102,’bala’)
Output:
90 120 bala
c. Default parameters :
Python allows function parameters to have default values; if
the function is called without the argument, the argument gets its
default values in function definition.
Example :
def student (name,age=17):
print(name,age)
student(“kumar”)
student(“ajay”)
Output:
Kumar 17
Ajay 17
Example :
def student(name,*mark):
print(name,mark)
student(“bala”,102,90)
Output :
bala(102,90)
Global scope :
The scope of variable refers to the places that you can see
or access a variable.
A variable with global scope can be used anywhere in the
program.
It can be created by defining a variable outside the
function.
Example:
a=50------------------------------------>global variable
def add():
b=20---------------------------->local variable
c=a+b
print(c)
def sub():
b=30---------------------------->local variable
c=a-b
print(c)
Output :
70
20
Local scope :
A variable with local scope can be used within the
function.
Example :
def add():
b=20
c=a+b
print(c)
Output :
70
5. FUNCTION COMPOSITION :
I. Function composition is the ability to call one function
from within another function.
II. It is the way of combining functions such that the result
of each function is passed as the arguments of the next
function.
III. In other words,the output of one function is given as
the output of the other function is known as function
composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900
6. RECURSION :
A function calling itself till it reaches the base value-stop point of
a function call. Example factorial of a given number using
recursion function
Example :
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=int(input(“Enter n value:”))
fact=fact(n)
print(“fact is”,fact)
Output :
Enter n value: 5
120
#sum of n numbers using recursion
def sum(n):
if(n==1):
return 1
else:
return n*sum(n-1)
n=int(input(“Enter n value:”))
sum=sum(n)
print(“sum is”,sum)
Output :
Enter n value:10
Sum is 55
STRINGS :
▪ Strings
▪ String slices
▪ Immutability
▪ String functions and methods
▪ String modules
STRINGS :
• String is defined as sequence ofcharacters represented in
quotation marks(either single quotes(‘) or double quotes
(“) ).
• An individual character in 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 the contents of the
string can’t be changed after it is created.
• Python will get an input at the run time by default as a
string.
• Python does not support character data type. A string of
size 1 can be treated as a character.
1. Single quotes (‘ ‘)
2. Double quotes(“ “)
3. Triple quotes(“”” “””)
OPERATIONS ON A STRING :
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
1. INDEXING :
The initial character or substring takes zero as its index
and the rest are numbered sequentially.
SYNTAX :
String_variable[index number]
String A H E L L O
Positive
index 0 1 2 3 4
Negative
index -5 -4 -3 -2 -1
2. SLICING :
• Accessing some part of a string or sub-string is known as
slicing. This can be done by specifying an index range.
• A segment of a string is called a slice. selecting a slice is
similar to selecting a character.
• The operator of slice indicates two types. They are :
1. Square brackets( “[ ]” )
2. Separated by colon( “ : “ )
• The operator colon are denoted [m:n]
• Including first but excluding the last.
Start------> m ; finish---------> n
Syntax :
String name[start : finish-1]
Example :
>>>a=”hello”
>>>print([0:4])-------------> hell
ILLUSTRATIVE PROGRAMS:
Square root using newtons method:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Output:
enter number to find Sqrt: 9
3.0
output
Enter a number1:8
Enter a number2:24
8
Exponent of number
def power(base,exp):
if(exp==1):
return(base)
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)
Output:
Enter base: 2
Enter exponential value:3
Result: 8
output:
the sum is 35
Linear search
a=[20,30,40,50,60,70,89]
print(a)
search=eval(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
Binary search
a=[20, 30, 40, 50, 60, 70, 89]
print(a)
search=eval(input("enter a element to search:"))
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")
output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
UNIT-4
LISTS
The syntax for accessing the elements of a list is the same as for accessing the
characters of a string—the bracket operator. The expression inside the brackets
specifies the index.
Remember that the indices start at 0:
Traversing a list
The most common way to traverse the elements of a list is with a for loop. The
syntax is the same as for strings:
List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
The first example repeats [0] four times. The second example repeats the list
[1, 2, 3] three times.
List slices
Since lists are mutable, it is often useful to make a copy before performing
operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
List methods
Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']
List methods are all void; they modify the list and return None
List Loop
In Python lists are considered a type of iterable . An iterable is a data type that
can return its elements separately, i.e., one at a time.
Eg:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
...print("Hi "+ name +"!")
Deleting elements
There are several ways to delete elements from a list. If you know the index of
the elementyou want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
pop modifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
If you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
As usual, the slice selects all the elements up to, but not including, the second
index.
Because list is the name of a built-in function, you should avoid using it as a
variable name. I also avoid l because it looks too much like 1. So that’s why I
use t.
The list function breaks a string into individual letters. If you want to break a
string into words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
An optional argument called a delimiter specifies which characters to use as
word boundaries.
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter) ['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and concatenates the
elements. join is a string method, so you have to invoke it on the delimiter and
pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
In this case the delimiter is a space character, so join puts a space between
words. To concatenate strings without spaces, you can use the empty string, '',
as a delimiter.
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the
same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print a
[17, 2, 3]
Cloning Lists
Cloning means making an exact but separate copy
create a new list and copy every element
Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)
List arguments
When you pass a list to a function, the function gets a reference to the list. If the
function modifies a list parameter, the caller sees the change. For example,
delete_head removes the first element from a list:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
The parameter t and the variable letters are aliases for the same object.
TUPLES
Tuples are immutable
A tuple is a sequence of values. The values can be any type, and they are
indexed by integers, so in that respect tuples are a lot like lists. The important
difference is that tuples are immutable. Syntactically, a tuple is a comma-
separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Most list operators also work on tuples. The bracket operator indexes an
element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
Tuple assignment
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 you 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. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1
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.
Dictionaries have a method called items that returns a list of tuples, where each
tuple is a key-value pair.
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
Dictionaries:
❖
Dictionary is an unordered collection of elements. An element in
dictionary has a key: value pair.
❖
All elements in dictionary are placed inside the curly braces i.e. { }
❖
Elements in Dictionaries are accessed via keys and not by their
position.
❖
The values of a dictionary can be any data type.
❖
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Methods in dictionary:
Difference between List, Tuples and dictionary:
Advanced list processing:
List Comprehension:
❖
List comprehensions provide a concise way to apply operations on a list.
❖
It creates a new list in which each element is the result of applying a
given operation in a list.
❖
It consists of brackets containing an expression followed by a “for”
clause, then a list.
❖
The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
Illustrative programs:
Selection sort
a=input("Enter list:").split()
a=list(map(eval,a))
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)
Output
Enter list:23 78 45 8 32 56
[8,2 3, 32, 45,56, 78]
Insertion sort
a=input("enter a list:").split()
a=list(map(int,a))
for i in a:
j = a.index(i)
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
output
enter a list: 8 5 7 1 9 3
[1,3,5,7,8,9]
Merge sort
def merge(a,b):
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
output
[3,9,10,27,38,43,82]
LISTS, TUPLES AND DICTIONARIES
1. What is a list?
A list is an ordered set of values, where each value is identified by an index.
The values that make up a list are called its elements. Lists are similar to strings,
which are ordered sets of characters, except that the elements of a list can have
any type.
3. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]
11. Write a program in Python returns a list that contains all but the first
element of the given list.
def tail(list): return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
print rest [2, 3]
LIST OPERATIONS
The + operator concatenates lists
: >>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c [1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST SLICES
The slice operator also works on lists:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] ['b', 'c']
>>> t[:4] ['a', 'b', 'c', 'd']
>>> t[3:] ['d', 'e', 'f']
If we omit the first index, the slice starts at the beginning. If we omit the
second, the slice goes to the end.
So if we omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing
operations that fold, spindle or mutilate lists. A slice operator on the left side of
an assignment can update multiple elements:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t ['a', 'x', 'y', 'd', 'e', 'f,]
>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0, 'n']
We can assign new values to slices of the lists, which don't even have to be the
same length:
It's even possible to append items onto the start of lists by assigning to an empty
slice:
Similarly, you can append to the end of the list by specifying an empty slice
after the end:
The right-hand side of a list assignment statement can be any iterable type:
With slicing you can create copy of list since slice returns a new list:
Note, however, that this is a shallow copy and contains references to elements
from the original list, so be careful with mutable types:
>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]
Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get
every n-th occurrence of a list, one would use the :: operator. The syntax is a:b:n
where a and b are the start and end of the slice to be operated upon.
>>> list = [i for i in range(10) ]
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[::2] [0, 2, 4, 6, 8]
list[1:7:2] [1, 3, 5]
2. Explain in detail about list methods and list loops with examples.
Python provides methods that operate on lists. Some of the methods are
• Append()
• Extend()
• Sort()
• Pop()
For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t ['a', 'b', 'c', 'd']
Extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified. sort arranges the elements of the list from
low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t ['a', 'b', 'c', 'd', 'e']
Remove the item in the list at the index i and return it. If i is not given, remove
the the last item in the list and return it.
>>>list = [1, 2, 3, 4]
>>>a = list.pop(0)
>>> list [2, 3, 4]
>>> a
List methods are all void; they modify the list and return None.
LIST LOOPS
Here are two functions that both generate ten million random numbers, and
return the sum of the numbers.
They both work.
import random
joe = random.Random()
def sum1():
""" Build a list of random numbers, then sum them """ # Generate one random
˓→number
xs = []
for i in range(10000000):
num = joe.randrange(1000 )
xs.append(num)
# Save it in our list
tot = sum(xs)
return tot
def sum2():
""" Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = joe.randrange(1000)
tot += num
return tot
print(sum1())
print(sum2())
MUTABILITY
Unlike strings, lists are mutable, which means we can change their elements.
Using the bracket operator on the left side of an assignment, we can update one
of the elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit [’pear’, ’apple’, ’orange’]
With the slice operator we can update several elements at once:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = [’x’, ’y’]
>>> print list [’a’, ’x’, ’y’, ’d’, ’e’, ’f’] \
We can also remove elements from a list by assigning the empty list to them:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = []
>>> print list [’a’, ’d’, ’e’, ’f’]
And we can add elements to a list by squeezing them into an empty slice at the
desired location:
>>> list = [’a’, ’d’, ’f’]
>>> list[1:1] = [’b’, ’c’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’f’]
>>> list[4:4] = [’e’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
DICTIONARIES
A dictionary is like a list, but more general. In a list, the indices have to be
integers; in a dictionary they can be (almost) any type. You can think of a
dictionary as a mapping between a set of indices (which are called keys) and a
set of values. Each key maps to a value. The association of a key and a value is
called a key-value pair or sometimes an item. As an example, we’ll build a
dictionary that maps from English to Spanish words, so the keys and the values
are all strings.
The function dict creates a new dictionary with no items. Because dict is the
name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print eng2sp {}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the
dictionary, you can use square brackets: >>> eng2sp['one'] = 'uno' This line
creates an item that maps from the key 'one' to the value 'uno'. If we print the
dictionary again, we see a key-value pair with a colon between the key and
value:
>>> print eng2sp {'one': 'uno'}
This output format is also an input format. For example, you can create a new
dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same
example on your computer, you might get a different result. In general, the
order of items in a dictionary is unpredictable. But that’s not a problem because
the elements of a dictionary are never indexed with integer indices. Instead, you
use the keys to look up the corresponding values:
>>> print eng2sp['two'] 'dos'
The key 'two' always maps to the value 'dos' so the order of the items doesn’t
matter. If the key isn’t in the dictionary, you get an exception:
>>> print eng2sp['four'] KeyError: 'four'
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether something appears as
a key in the dictionary (appearing as a value is not good enough).
>>> 'one' in eng2sp True
>>> 'uno' in eng2sp False
To see whether something appears as a value in a dictionary, you can use the
method values, which returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
The in operator uses different algorithms for lists and dictionaries. For lists, it
uses a search algorithm, as in Section 8.6. As the list gets longer, the search
time gets longer in direct proportion. For dictionaries, Python uses an algorithm
called a hashtable that has a remarkable property: the in operator takes about the
same amount of time no matter how many items there are in a dictionary
Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the
following dictionary contains the names of various fruits and the number of
each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’:
312}
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory[’pears’]
>>> print inventory {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
Or if we’re expecting more pears soon, we might just change the value
associated with pears:
>>> inventory[’pears’] = 0
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value
pairs:
>>> len(inventory) 4
DICTIONARY METHODS
A method is similar to a function—it takes arguments and returns a value— but
the syntax is different. For example, the keys method takes a dictionary and
returns a list of the keys that appear, but instead of the function syntax
keys(eng2sp), we use the method syntax eng2sp.keys().
>>> eng2sp.keys() [’one’, ’three’, ’two’]
This form of dot notation specifies the name of the function, keys, and the name
of the object to apply the function to, eng2sp. The parentheses indicate that this
method has no parameters. A method call is called an invocation; in this case,
we would say that we are invoking keys on the object eng2sp.
The values method is similar; it returns a list of the values in the dictionary:
>>> eng2sp.values() [’uno’, ’tres’, ’dos’]
The items method returns both, in the form of a list of tuples—one for each key-
value pair:
>>> eng2sp.items() [(’one’,’uno’), (’three’, ’tres’), (’two’, ’dos’)]
The syntax provides useful type information. The square brackets indicate that
this is a list. The parentheses indicate that the elements of the list are tuples. If a
method takes an argument, it uses the same syntax as a function call. For
example, the method has key takes a key and returns true (1) if the key appears
in the dictionary:
>>> eng2sp.has_key(’one’)
True
>>> eng2sp.has_key(’deux’)
False
If you try to call a method without specifying an object, you get an error. In this
case, the error message is not very helpful:
>>> has_key(’one’) NameError: has_key 108
List comprehensions
List comprehensions provide a concise way to create lists. It consists of brackets
containing an expression followed by a for clause, then zero or more for or if
clauses. The expressions can be anything, i.e., all kinds of objects can be in
lists. The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses which follow it. The list comprehension always
returns a result list.
Syntax
The list comprehension starts with a '[' and ']', to help you remember that the
result is going to be a list.
The basic syntax is
[ expression for item in list if conditional ]
This is equivalent to:
for item in list:
if conditional:
expression
List comprehension is a method to describe the process using which the list
should be created. To do that, the list is broken into two pieces. The first is a
picture of what each element will look like, and the second is what is done to
get it.
For instance, let's say we have a list of words:
listOfWords = ["this","is","a","list","of","words"]
To take the first letter of each word and make a list out of it using list
comprehension:
>>> listOfWords = ["this","is","a","list","of","words"]
>>> items = [ word[0] for word in listOfWords ]
>>> print items
['t', 'i', 'a', 'l', 'o', 'w']
List comprehension supports more than one for statement. It will evaluate the
items in all of the objects sequentially and will loop over the shorter objects if
one object is longer than the rest.
>>> item = [x+y for x in 'cat' for y in 'pot']
>>> print item
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
List comprehension supports an if statement, to only include members into the
list that fulfill a certain condition:
>>> print [x+y for x in 'cat' for y in 'pot']
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>>print [x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ] ['
cp', 'ct', 'ap', 'at']
print [x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ] ['cp', '
co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt']
Merge sort:
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)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Quicksort:
from random import randrange
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in xrange(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = randrange(start, end + 1)
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
def sort(lst):
quick_sort(lst, 0, len(lst) - 1)
return lst
print sort([-5, 3, -2, 3, 19, 5])
print sort([345,45,89,569,23,67,56,90,100])
Unit -5
FILES
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a file
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we
want to read 'r', write 'w' or append 'a' to the file. We also specify if we want
to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading
from the file. On the other hand, binary mode returns bytes and this is the
mode to be used when dealing with non-text files like image or exe files.
Python File Modes
Mode : Description
'r' : Open a file for reading. (default)
'w' : Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
'x' : Open a file for exclusive creation. If the file already exists, the operation
fails.
'a' : Open for appending at the end of the file without truncating it. Creates a
new file if it does not exist.
't' : Open in text mode. (default)
'b' : Open in binary mode.
'+' : Open a file for updating (reading and w
Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done
using the close() method.
Python has a garbage collector to clean up unreferenced objects but, we must
not rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are
performing some operation with the file, the code exits without closing the
file. A safer way is to use a try...finally block.
try:
f= open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
If the file already exists, opening it in write mode clears out the old data and
starts fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>>fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds
the new data to the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
Format operator
The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted. The result is a
string.
For example, the format sequence '%d' means that the second operand should
be formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
EXCEPTION
>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it
to the calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and
an exception occurs in function C. If it is not handled in C, the exception passes
to B and then to A.
If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.
Catching Exceptions in Python
MODULES
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file,
which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it
executes the test code at the bottom. Normally when you import a module, it
defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idiom: if
__name__ == '__main__':
print linecount('wc.py')
__name__ is a built-in variable that is set when the program starts. If the
program is running as a script, __name__ has the value __main__; in that case,
the test code is executed. Otherwise, if the module is being imported, the test
code is skipped.
Eg:
# import module import calendar
yy= 2017
mm = 8
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)
If this construct seems lengthy, we can import the module without the package
prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)
ILLUSTRATION PROGRAM
1. Word Count
import sys
file=open("/Python27/note.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))
A text file is a file that contains printable characters and whitespace, organized
in to lines separated by newline characters.
7. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops
execution and prints an error message. For example, dividing by zero creates an
exception:
print 55/0
ZeroDivisionError: integer division or modulo
8. What are the error messages that are displayed for the following
exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a. IndexError: list index out of range
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'
10. How do you handle the exception inside a program when you try to
open a non-existent file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
The try statement executes the statements in the first block. If no exception
occurs, then except statement is ignored. If an exception of type IOError occurs,
it executes the statements in the except branch and then continues.
12. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an
error. It takes two arguments: the exception type and specific information about
the error.
18. What is the special file that each package in Python must contain? Each
package in Python must contain a special file called __init__.py
20. How do you use command line arguments to give input to the
program?
Python sys module provides access to any command-line arguments via
sys.argv. sys.argv is the list of command-line arguments. len(sys.argv) is the
number of command-line arguments.
COPYING CONTENTS OF ONE FILE TO ANOTHER
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()