Unit 3,4,&5 Material
Unit 3,4,&5 Material
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, local and global scope, function composition, recursion; Strings: string slices, immutability,
string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd,
exponentiation, sum an array of numbers, linear search, binary search.
BOOLEAN VALUES
The Boolean data type is a data type that has one of two possible values.
o True
o False
All other values are considered true — so objects of many types are always true.
We can also check the data type of True or False with the help of ‘type’ function.
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
1
OPERATORS IN PYTHON WITH SUITABLE EXAMPLES [Dec/Jan 2018]
Operators are a special symbol that specifies an operation to be performed on the operands.
Operators in programming languages are taken from mathematics.
An operator may have one or two operands.
An operand is one of the inputs (arguments) of an operator.
Those operators that work with only one operand are called unary operators.
Those who work with two operands are called binary operators.
Ex. a+b,
Here a and b are operands,+ operator.
Types of operators:
1. Arithmetic Operators ( + ,-,*,/,%,//,**)
2. Comparison (Relational) Operators (>,<,==,!=,>=,<=)
3. Logical Operators (and,or,not)
4. Assignment Operators (=,+=,-=,*=,/=,%=,**=)
5. Bitwise Operators (&, |, ^, ~)
6. Membership Operators (in ,not in)
7. Identity Operators (is, is not)
1. Arithmetic Operators
• Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc. ( + ,-,*,/, %, //(floor division), **(exponentiation)).
Example:
x = 15 OUTPUT:
y=4 x + y = 19
print(“ x + y = “, x+y) x - y = 11
print(“ x - y = “, x-y) x * y = 60
print(“ x * y = “, x*y) x / y = 3.75
print(“ x / y = “, x/y) x%y = 3
print(“ x % y = “, x%y) x // y = 3
print(“ x // y = “, x//y) x ** y = 50625
print(“ x ** y = “, x**y)
2
2. Comparison operators
• Comparison operators are used to compare two or more operands. These are also known as
Relational Operators.
• Relational operators are used in decision making process.
• It either returns True or False according to the condition.
• The comparison operators are >,<,==,!=,>=,<=.
For example,
x = 10
OUTPUT:
y = 12
print(“x > y is”,x>y) x > y is False
print(“x < y is”,x<y) x < y is True
print(“x == y is”,x==y) x == y is False
print(“x != y is”,x!=y) x != y is True
x >= y is False
print(“x >= y is”,x>=y)
x <= y is True
print(“x <= y is”,x<=y)
3. Logical operators:
Logical operators are used to combine the results of two or more conditions.
Logical operators are and, or, not operators.
Python's logical operators mostly use boolean operands to produce boolean results.
3
Truth Table:
Example:
x = True
Output:
y = False
print(“x and y is”, x and y) x and y is False
print(“x or y is”, x or y) x or y is True
print(“not x is”, not x) not x is False
4. Assignment operators
Assignment operators are used in python to assign values to variables.
(=,+=,-=,*=,/=,%=,**=,>>=,<<=,&=,|=,^=)
Syntax:
Variable=expression (or) value
Ex.1
a = 21
b = 10 Output:
c=0 Line 1 - Value of c is 21
c += a Line 2 - Value of c is
print( "Line 1 - Value of c is ", c)
5842587018385982521381124421
c **= a
print( "Line 2 - Value of c is ", c)
5. Bitwise operator
It works on bits and performs bit by bit operation. It operates on integers only.
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal,
decimal or hexadecimal symbols are only notations of the same number.
Bitwise operators work with bits of a binary number. We have binary logical operators and shift
operators.
Bitwise operators are seldom used in higher level languages like Python.
4
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Example:
a = 60
b = 13
c=0
c=a&b
print ("Line 1 - Value of c is ", c)
c=a|b
Output:
print ("Line 2 - Value of c is ", c)
c=a^b Line 1 - Value of c is 12
print ("Line 3 - Value of c is ", c) Line 2 - Value of c is 61
c = ~a Line 3 - Value of c is 49
print ("Line 4 - Value of c is ", c) Line 4 - Value of c is -61
c = a << 2 Line 5 - Value of c is 240
print ("Line 5 - Value of c is ", c) Line 6 - Value of c is 15
c = a >> 2
print ("Line 6 - Value of c is ", c)
6. Membership operators:
Ex. Output:
x = “Hello world” True
y = {1:'a', 2:'b'} True
print('H' in x) True
print('hello' not in x)
print(1 in y)
5
7. Identity Operators:
Identity operators compare the memory locations of two objects.(is ,is not)
For ex.
OUTPUT:
a = 20
b = 20 Line 1 - a and b have same identity
if ( a is b ):
print( "Line 1 - a and b have same identity“)
else:
print ("Line 1 - a and b do not have same identity")
Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given below.
Operator Description
The exponent operator is given priority over all
**
the others used in the expression.
~+- The negation, unary plus, and minus.
The multiplication, divide, modules, reminder,
* / % //
and floor division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
Comparison operators (less than, less than
<= < > >=
equal to, greater than, greater then equal to).
<> == != Equality operators.
= %= /= //= -= +=
Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
6
CONDITIONAL OR DECISION MAKING STATEMENTS [Dec/Nov 2018]
Conditional Statements decides the order in which statements or blocks of code are executed at
runtime based on a condition.
Conditional Statements are also called as Selection Structure, Decision Making Statements and
Control Flow.
In a program all the instructions are executed sequentially by default, when no repetitions of some
calculations are necessary in some situation we may have to change the execution order of
statements based on condition or to repeat a set of statements until certain conditions are met.
Conditional Statements:
a) if statement(conditionals)
b) if –else statement(alternative)
c) if –elif –else(chained conditional)
a) if statement(conditionals)
The if statement is a decision making statement. It is used to control the flow of execution of
the statements and also used to test logically whether the condition is true or false.
The program evaluates the test condition and executes the statements only if the test condition
is True.
If the test condition is False, the statements are not executed.
Properties of an if statement:
i. if the condition is true, then the simple or compound condition statements are executed.
ii. If the condition is false, it does not do anything.
iii. The condition is given in parenthesis and must be evaluated as true (non-zero value) or
false (zero value).
Syntax: Flow Chart:
if (expression):
True Statements
.
.
.
x=int(input("enter number"))
if ( x>0):
print ("x is positive")
7
b) if –else statement
It evaluates test condition and executes the True statement block only when the test
condition is true.
If the condition is False, false statements block is executed.
Indentation is used to separate the blocks.
Syntax: Flow charts:
if(condition):
True Statements
else:
False Statments
if condition 1:
True statement block for cond 1
elif condition 2:
True statement block for cond 2
else:
False statement Block
8
LOOPING OR ITERATING STATEMENTS: [DEC/NOV 2018]
The loop is defined as the block of statements which are repeatedly executed for certain number
of times.
The loop consists of 2 parts.
1.body of the loop
2.control statement.
Any looping statement would include the following steps:
1. Initialization of a condition variable.
2. Test the control statements
3. Executing the body of the loop depending on the condition
4. Updating the condition variable.
1. while loop
• It is a repetitive control structure, used to execute the statements within the body, until the
condition becomes false.
• The while loop is an entry controlled loop statement, which means the condition is evaluated
first and if it is true, then the body of the loop is executed.
• After executing the body of the loop, the condition is once again evaluated, if it is true, the loop
continues until the condition finally becomes false and the control is transferred out of the loop.
while (expression):
statement(s)
9
2. for loop:
The for loop is another repetitive control structure, and is used to execute a set of instructions
repeatedly, until the condition becomes false.
In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other iterable
objects such as range.
The Initializing Counter Variable, Increment or Decrement and Condition checking is done in for
statement itself, where as other control structures are not offered all these features in one statement.
sum=0
for i in range(11): output:
sum=sum+i sum of numbers upto 10 is: 55
print(“sum of numbers upto 10 is :”,sum)
OUTPUT:
Ex3. print the pyramid of numbers. 0 1
for i in range(5): 1 10
print(“{0:3} {1:16}”.format(i, 10**i)) 2 100
3 1000
4 10000
10
LOOP CONTROL STATEMENTS IN DETAIL? (UNCONDITIONAL STATEMENTS)
[Dec/Nov 2018]
Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
Python supports the following control statements.
1.break statement
2.continue statement
3.pass statement
Control
Description
statement
Terminates the loop statement and transfers execution to the statement
break
immediately following the loop.
Causes the loop to skip the reminder of its body and immediately
continue
retest its condition prior to reiterating.
The pass statement in python is used when a statement is required
pass
syntactically but you do not want any command or code to execute.
1.break statement:
The break statement is used to terminate the loop.
When the keyword break is used inside any python loop, control is automatically transferred to
the first statement after the loop. A break is usually associated with an if statement.
The break statement can be used in both while and for loops.
Ex.
output:
Current Letter : P
Current Letter : y
Current Letter : t
11
2.continue:
In some situations, we want to take the control to the beginning of the loop, by passing the
statements inside the loop which have not yet been executed, for this purpose the continue is used.
When the statement continue is encountered inside any python loop control automatically passes
to the beginning of the loop.
The continue statement can be used in both while and for loops.
Example:
for letter in 'Python':
if letter == 'h':
continue
print(“Current Letter :”, letter)
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
3. pass statement:
It is used when a statement is required syntactically but you do not want any command or code to
execute.
The pass statement is a null operation; nothing happens when it executes. We generally use it as
a placeholder.
Syntax: pass
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future.
They cannot have an empty body. The interpreter would complain. So, we use the pass statement
to construct a body that does nothing.
12
FRUITFUL FUNCTIONS
A function that returns a value is called fruitful functions.
The return statement is followed by an expression which is evaluated.
Its result is returned to the caller as the “fruit” of calling function.
RETURN VALUE:
Return value means the result of a function.
Return takes zero, values or an expression. Default value is none.
If a function is called using an expression, the return value is the value of the expression.
The value can be returned from a function using the keyword return.
Syntax:
return[expression _list]
For example,
#Area of Circle
def Area_Circle(r):
return 3.14*r*r
r=int(input("enter r"))
print("ans=",Area_Circle(r)) function calling
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def big(a,b):
if(a>b):
return a
else:
return b
print(big(5,8))
In the above ex, since these return statements are in an alternative conditional, only one will be
executed. As soon as one is executed, the function terminates without executing any subsequent
statements.
Code that appears after a return statement, or any other place the flow of execution can never
reach, is called dead code.
PARAMETERS:
Input values (parameters) are passed from function calling line to function definition block, these
inputs are called as arguments or parameters.
Here is an example of a user-defined function that takes an argument:
def print_twice(bruce):
print (bruce)
print (bruce)
This function assigns the argument to a parameter named bruce. When the function is called, it
prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
13
Ex 1 >>> print_twice('Spam') #String
Spam
Spam
Ex 2 >>> print_twice(17) #Integer
17
17
Ex 3 >>> print_twice(math.pi) #Pre-defined value of ‘pi’
3.14159265359
3.14159265359
Ex 4 >>> print_twice('Spam '*4) #String 4 times
Spam Spam Spam Spam
Spam Spam Spam Spam
Ex 5 Use a variable as an argument: #Variable value
>>> michael = 'Eric, the half a bee’
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
The name of the variable we pass as an argument (michael) has nothing to do with the name of the
parameter (bruce). It doesn’t matter what the value was called back home (in the caller)
Here in print_twice, we call everybody bruce.
1. global variables:
Variables that are defined outside a function have a global scope.
2. local variables:
Variables that are defined inside a function body have a local scope.
Example
14
CALL-BY-VALUE vs. CALL-BY-REFERENCE
Call by Value: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory locations.
So any changes made inside functions are not reflected in actual parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.
FUNCTION COMPOSITION
Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function.
For example, the composition of two functions f and g is denoted f(g(x)). x is the argument of g,
the result of g is passed as the argument of f and the result of the composition is the result of f.
Example:
def add(a,b):
return a+b
def mul(c,num):
return c*num
def mainfun(x,y):
z=add(x,y)
result=mul(z,10)
return result
Output:
mainfun(8,8)
160
15
RECURSION
Recursion is a way of programming or coding a problem, in which a function calls itself one or
more times in its body.
Usually, it is returning the return value of this function call. If a function definition fulfils the
condition of recursion, we call this function a recursive function.
Syntax:
Function1():
Function1()
the function1() is called themselves continuously, so the function is in recursion manner.
Advantages:
1. The code look clean and elegant.
2. Large problems broken down into small problems
Disadvantages:
1. Logic is hard to follow.
2. It takes more memory.
3. It is hard to debug.
Example 1: Factorial of a number
def fact(n):
if (n == 1):
return 1 Output:
else: Enter a number 3
return n * fact(n-1) Factorial is 6
16
STRINGS
A string is a sequence of characters, enclosed within single-quotes (‘ ’) or double quotes(“ ”).
Strings are immutable, which means you can’t change an existing string.
For ex.
>>>fruit=”banana”
>>>print(fruit)
banana
String index: The expression in brackets is called an index.
The index indicates which character in the sequence to be displayed. The index starts at 0.
Example
>>>fruit=”banana”
>>>print(fruit[1])
a
>>>fruit=’banana’
>>>print(fruit[4])
n
As an index, we can use an expression that contains variables and operators.
>>>fruit=’banana’
>>>i=1
>>>fruit[i]
a
>>>fruit[i+1]
n
The value of the index has to be an integer.
>>>letter[1.5]
Type error: string indices must be integers
String slices:
A segment of a string is called a slice. This can be represented using slicing operator ‘:’.
Example 1.
Output:
s= “Monty Python!” Monty
print (s[0:5]) Python
print(s[6:12]
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”
character, including the first but excluding the last.
o print (s[0:5]) #Monty
If you omit the first index (before the colon), the slice starts at the beginning of the string.
o print (s[:5]) #Monty
17
If you omit the second index, the slice goes to the end of the string.
o print (s[6:]) #Python
If the first index is greater than or equal to the second the result is an empty string, represented
by two quotation marks.
o print (s[7:5]) #
An empty string contains no characters and has length 0, but other than that, it is the same as
any other string.
Accessing strings:
Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
For example −
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
OUTPUT:
var1[0] : H
var2[1:5]: ytho
len( ):
len() is a built-in(pre-defined) function that returns number of characters in a string.
>>>fruit=’banana’
>>>len(fruit)
6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length-1]
Since we started counting at zero, the six letters are numbered 0 to 5.
>>> print last
a
Alternatively, you can use negative indices, which count backward from the end of the string. The
expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
Ex.
>>>fruit=’banana’
>>>print(fruit[-1]
a
>>>print(fruit[-6]
b
18
Traversal with a for loop
A lot of computations involve processing a string one character at a time. Often they start at the
beginning, select each character in turn, do something to it, and continue until the end. This pattern
of processing is called a traversal.
Ex1: One way to write a traversal is with a while loop:
index = 0 OUTPUT:
fruit=”banana” b
while( index < len(fruit)): a
letter = fruit[index] n
print( letter ) a
index = index + 1 n
a
This loop traverses the string and displays each letter on a line by itself
Immutability:
The reason for the error is that strings are immutable, which means you can’t change an existing
string. The best you can do is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print (new_greeting Jello, world!)
This example concatenates a new first letter onto a slice of greeting. It has no effect on the original
string.
Python has several built-in functions associated with the string data type.
19
str.isalnum() - String consists of only alphanumeric characters (no symbols)
str.isalpha() - String consists of only alphabetic characters (no symbols)
str.islower() - String‘s alphabetic characters are all lower case
str.isnumeric()- String consists of only numeric characters
str.isspace() - String consists of only whitespace characters
Ex.
Book1 = "PYTHON PROGRAMMING"
book2 = "Python Program Book"
poem = "problem solving python"
print(book1.islower( )) OUTPUT:
False
print(book1.isupper( )) True
print(book2.istitle( )) True
print(book2.isupper( )) False
print(poem.istitle( )) False
print(poem.islower( )) True
join( ) method:
The str.join() method will concatenate two strings, but in a way that passes one string
through another.
Syntax:
str.join(Sequence)
Ex.
s = "-";
seq = ("a", "b", "c");
print s.join( seq )
output:
a-b-c
split( ) method:
The method split() returns a list of all the words in the string
Ex.
words = "This is random text"
words2 = words . split(" ")
print(words2)
output:
['This', 'is', 'random', 'text']
20
replace( ) method:
The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Example:
song = 'cold, cold heart'
print (song . replace('cold', 'hurt'))
output:
hurt, hurt heart
STRING MODULES
# String module
import string as str
text="Monty Python's Flying Circus"
OUTPUT:
print("upper", "=>",str.upper(text))
print( "lower", "=>",str.lower(text)) upper => MONTY PYTHON'S FLYING CIRCUS
print("split", "=>",str.split(text)) lower => monty python's flying circus
print("join", "=>", str.join(str.split(text),"+")) split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
print("replace", "=>",str.replace(text,"Python", "Java"))
replace => Monty Java's Flying Circus
print("find", "=>",str.find(text, "Python")), find => 6
print("count", "=>",str.count(text, "n")) count => 3
21
ILLUSTRATIVE PROGRAMS:
1. Square root of a number
def newtonsqrt(n):
approx=0.5*n
better=0.5*(approx+n/approx)
while(better!=approx):
approx=better
better=0.5*(approx+n/approx)
return approx Output:
n=int(input("Enter the number:")) Enter the number:81
result=newtonsqrt(n) The square root for the given number is: 9.0
print("The square root for the given number is:",result)
2. gcd of a number
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
3. Exponentiation
import math Output:
x=int(input("Enter X:")) Enter X:3
y=int(input("Enter Y:")) EnterY:2
print("Power:",math.pow(x,y)) Power :9
4. linear search
n=int(input("Enter the limit:"))
list=[ ]
print("Enter the element one by one:") Output:
for i in range(0,n): Enter the limit:5
x=int(input()) Enter the element one by one:
list.append(x)
34
key=int(input("Which element to search:"))
12
count=0
for i in range(0,n): 45
if(key==list[i]): 67
count=count+1 32
if(count>0): Which element to search:45
print("Element found") Element found
else:
print("Element not found")
22
5. Binary search
sum=0
i=0
a=[10,20,30,40]
for i in range(4):
sum=sum+a[i]
print(sum)
23
Additional Programs:
1.Write a python program to find factorial of a number without recursion and without recursion
[Dec /Jan 2018]
without recursion:
n=int(input("Enter number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("Factorial of the number is: ")
print(fact)
with recursion:
def fact(n):
if (n == 1):
return 1
else:
return n * fact(n-1)
x=int(input("enter a number:"))
print("Facorial is:",fact(x))
Output:
enter a number : 3
Factorial is: 6
def fibo(n):
if(n <= 1): Output:
return n Enter number of terms: 6
else: Fibonacci sequence:
return(fibo(n-1) + fibo(n-2)) 0
1
1
n = int(input("Enter number of terms:")) 2
print("Fibonacci sequence:") 3
for i in range(n): 5
print(fibo(i))
24
UNIT IV LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced
list processing - list comprehension; Illustrative programs: simple sorting, histogram, Students marks
statement, Retail bill preparation.
LISTS
Like a string, a list is a sequence of values. In a string, the values are characters; In a list, they can be
of any type. The values in a list are called elements or sometimes items.
A list need not be homogenous. The elements of a list don’t have to be the same type. A list can contain
different data type items such as string, integer, float, real and another list. Each and every item has its unique
index.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ ]):
>>>L1=[10, 20, 30, 40] #List of four Integers
>>>L2=[‘Apple’, ‘Banana’, ‘Orange’] #List of three Strings
>>>L3=[‘spam’, 2.0, 5, [10, 20]] #list with string, a float, an integer, and another list
>>>L4=[] #A list that contains no elements is called an empty list;
Mutability in Lists
To access the elements of a list the bracket operator is used. The expression inside the brackets specifies
the index. The indices starts at 0.
Any integer expression can be used as an index. If an index has a negative value, it counts backward
from the end of the list.
>>> L2=[‘Apple’, ‘Banana’, ‘Orange’]
>>> L2[0]
‘Apple’
Unlike strings, lists are mutable. We can delete or replace the items or elements in the list.
>>> L2[1]= ‘Grapes’ #replaces ‘Banana’
>>> L2
[‘Apple’, ‘Grapes’, ‘Orange’]
Updating list
Single or multiple elements can be updated in a list by giving the slice on the lefthand side of the
assignment operator and also can add the elements in a list with the append() method.
Example.py
s=['Red','green','Blue','yellow','Purple']
print("value at index 2:",s[2])
Output:
s[2]='Lavender'
print(s) value at index 2: Blue
s.append('Orange') ['Red', 'green', 'Lavender', 'yellow', 'Purple']
print(s) ['Red', 'green', 'Lavender', 'yellow', 'Purple', 'Orange']
Example.py
s=['Red','green','Blue','yellow','Purple']
print(s) Output:
del s[2] ['Red', 'green', 'Blue', 'yellow', 'Purple']
print(s)
['Red', 'green', 'yellow', 'Purple']
s.remove('yellow')
print(s) ['Red', 'green', 'Purple']
LIST OPERATIONS
List Operations:
List respond to the + and * operators much like strings; they mean concatenation and repetition here
too, expect that the result is a new list, not a string.
LIST SLICES
We can access a range of items in a list by using the slicing operator(colon :)
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the
end. So if you 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 modify lists.
Slicing can be bets visualized by considering the index to be between the elements as shown below. So if we
want to access a range, we need two index that will slice that portion from the list.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 Index
K E C P U B L I s h e r s
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Negative Index
LIST METHODS
List method is a method to list all the elements in the set. Python provides methods that operates on
lists. They are accessed as list.method( ).
Output:
[‘guava’ , ‘apple’ , ‘orange’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
2
[‘guava’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
append(): reverse():
This method appends / adds the pass object (v) to This method reverses the element in the list.
the existing list.
list1=[1,2,3,4] list1=[5,2,10,4]
list1.append(99) list1.reverse()
print(list1) print(list1)
Output: Output:
[1, 2, 3, 4, 99] [4, 10, 2, 5]
insert(): count():
This method insert the given element at the This method returns count of how many times
specified position. elements occur in the list.
list1=[1,2,3,4] list1=[5,2,10,4,3,5]
list1.insert(1,100) print(list1.count(5))
print(list1) Output:
Output: 2
[1, 100, 2, 3, 4]
index():
remove(): This method returns the index value of an element.
Removes the element from the list. If there is no
element then it displays error. list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.index(10))
list1.remove(4) Output:
print(list1) 2
Output:
[1, 2, 3] pop():
This method removes the element from the list at
extend(): the specified index. If the index value is not
This method appends the contents of the list. specified it removes the last element from the list.
list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.pop(4))
list1.extend([10,20,30]) print(list1.pop(7))
print(list1) Output:
Output: 3
[1, 2, 3, 4, 10, 20, 30] Traceback (most recent call last):
File "python", line 3, in <module>
sort(): IndexError: pop index out of range
This method sorts the element either alphabetically
or numerically. del():
list1=[5,2,10,4] Element to be deleted is mentioned using list name
list1.sort() and index.
print(list1)
Output: list1=[5,2,10,4,3]
[2, 4, 5, 10] del list1[3]
print(list1)
Output:
[5, 2, 10, 3]
LIST LOOP
Creating list using range( )
The range( ) functions returns an immutable sequence object of integers between the given start integer
to the stop integer.
It generates a list of numbers, which is generally used to iterate over with loops.
Syntax:
range(stop)
range(start, stop[, step])
where,
start – starting number of the sequence
stop – generate numbers up to, but not including this number.
step – integer value which determines the increment between each integer in the sequence
Example
A short hand for loop that will print all items in a list:
CLONING LISTS:
Cloning is different from aliasing. Aliasing just creates another name for the same list. Cloning creates
a new list with same values under another name. Taking any slice of a list creates a new list.
Example:
fruits=[“apples”,”pear”,”grapes”,”orange”,”mango”]
fruit_list=fruits
clonefruit=fruit_list[:]
clonefruit.append(“banana”) OUTPUT:
fruit_list[1]=”Lemon”
Original List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “Original List:”,fruits
print “Alias List:”,fruit_list Alias List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “clone List:”,clonefruit
clone List: [“apples”, “pear”, “grapes”, “orange”,
“mango”, “banana”]
LIST PARAMETERS
When you pass a list to a function ,the function gets a reference to the list.If the function modifies the
list,the caller sees the change.
For ex: delete _head removes the first element from a list:
def delete_head(t):
del t[0]
>>> letters=[‘a’,b’,’c’]
>>>delete_head(letters)
>>>letters
[‘b’,’c’]
The parameter‘t’ and the variable letters are aliases from the same object.
TUPLE
A tuple is a sequence of values. The values can be any type. They are immutable (i.e)objects whose
value is unchangeable once they are created.
Tuple can be created by putting different values separated by comma;the parantheses are optional.
Example:
No’s_Tuple=(1,2,3)
print No’s_tuple
Nested _tuple=(“string”,[‘list’,’in’,’tuple’],(‘tuple’,’in’,tuple’)) OUTPUT:
print Nested _tuple[0] (1, 2, 3)
print (Nested_tuple[1] string
print Nested _tuple[2] ['list', 'in', 'tuple']
Mixed_tuple=3,”kg”,”apples” ('tuple', 'in', 'tuple')
print(Mixed_tuple) (3, 'kg', 'apples')
Nos,measure,what=Mixed_tuple 3
print(Nos) kg
print(measure) apples
print(what)
OPERATIONS IN TUPLE
Two operators + and * is allowed in tuples. ‘+’ concatenates the tuples and ‘*’ repeates the tuple
elements a given number of times.
Ex:
t1= (1,2,3,4,7,8,9)
t2=(‘a’,)*5 OUTPUT:
t3=t1+t2
print “Add operation:”,t3 Add operation: (1, 2, 3, 4, 7, 8, 9, 'a', 'a', 'a', 'a', 'a')
print “Repeat operation:”,t2
Repeat operation: ('a', 'a', 'a', 'a', 'a')
SLICING AND INDEXING OF TUPLES:
a=(‘physics’,’chemistry’,1997,2000)
b=(1,2,3,4,5) OUTPUT:
c=(“x”,”y”,(10,4,5))
a[0]: physics
print “a[0]: ”,a[0]
c[2]: (10, 4, 5)
print ”c[2]: ”,c[2]
b[-2]: 4
print “b[-2]: ”,b[-2]
b[1:3]: (2, 3)
print “b[1:3]: ”,b[1:3]
Tuples are immutable; the elements cannot be changed. In lists the elements can be deleted.In
tuples elements cannot be deleted. However the entire tuple can be deleted using del.Similarly the elements
cannot be modified in a tuple.
In tuple we can replace one tuple with another, but can’t modify the elements.
TUPLE ASSIGNMENT
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
Example: a,b,c=1,2,3
The left side is a tuple of variable; the right side is a tuple of values. Each value is assigned to its
respective variable. The number of variables on the left and the right of the assignment operator must be same.
All the expression on the right side are evaluated before any of the assignment. This features make
tuple assignment quite versatile.
For Example:
>>> (a, b, c)=(1, 2, 3)
The built-in-function divmod takes two arguments and return a tuple of two values: the quotient and
remainder. You can store the result as a tuple:
>>> t=divmod(7,3)
>>>t
>>>(2,3)
def min_max(t)
return min(t),max(t)
max and min are build-in-functions that find the largest and smallest elements of a sequence.min_max
computes both and returns a tuple of two values.
DICTIONARIES
DICTIONARY
A dictionary is set of pairs of value with each pair containing a key and an item and is enclosed in curly
brackets. It is one of the compound data type like string, list and tuple.
In dictionary the index can be immutable data type.
It is a set of zero or more ordered pairs of key and value.
The value can be any type.
Each key may occur only once in the dictionary
No key may be mutable. A key may not be a list or tuple or dictionary and so on.
Example:
dict={} #empty dictionary
d1={1:'fruit ', 2:'ve getables', 3:'cereals'}
Example:
d1={1:'fruit',2:'vegetables',3:'cereals'}
d2=dict({'name':'aa','age':40})
print(d1[1])
print(d2)
Output:
fruit
{'name': 'aa', 'age': 40}
Deletion of elements
The elements in the dictionary can be deleted by using del statements.
The entire dictionary can be deleted by specifying the dictionary variable name.
Example:
del d1[1]#remove entry with key '1'
print(d1)
d1.clear()#remove all entries in dict
print(d1)
Output:
{2: 'vegetables', 3: 'cereals'}
{}
Updating elements
In dictionary the keys are always immutable.
The values are mutable that can be modified. New-key value pair can be inserted or deleted from the
dictionary.
Example:
d3={'name':'abc','dept':'ece'}
d3['name']='xxxx'
print(d3)
Output:
{'name': 'xxxx', 'dept': 'ece'}
Length:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> dict1 = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> len(dict1)
3
In Operator:
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).
>>> dict1= {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> 'one' in eng2sp
True
>>> 'uno' in dict1
False
To see whether something appears as a value in a dictionary, we 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
1) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate
keys are encountered during assignment, the last assignment wins.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Mani'}
print ("dict['Name']: ", dict['Name'])
Output:
dict['Name']: Mani
2) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
Following is a simple example −
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
If you use a dictionary in a for statement, it traverses the keys of the dictionary.
For example,
def histogram(s):
d=dict()
for c in s: Output:
if c not in d: >>> h = histogram('parrot')
d[c]=1 >>> print_hist(h)
else: a1
d[c]+=1 p1
return d r2
t1
print_hist prints each key and the corresponding value: o1
def print_hist(h):
for c in h:
print c, h[c]
3. str(dict)
Produces a printable string representation of a dictionary
For ex.
dict = {'Name': 'Zara', 'Age': 7} OUTPUT:
print ("Equivalent String :",str (dict))
Equivalent String : {'Age': 7, 'Name': 'Zara'}
4. type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.
For ex.
dict = {'Name': 'Zara', 'Age': 7};
print ("Variable Type :", type (dict))
METHODS IN DICTIONARY
1.dict.clear()
Removes all elements of dictionary dict
Ex.
dict = {'Name': 'Zara', 'Age': 7}
OUTPUT:
print ("Start Len :",len(dict))
dict.clear() Start Len : 2
print ("End Len :",len(dict))
End Len : 0
2. dict. copy()
Returns a shallow copy of dictionary dict
Ex.
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print ("The copied value:",dict2)
3.dict.values()
The method values() returns a list of all the values available in a given dictionary.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
print ("Values:",dict.values())
4.dict.key()
The method keys() returns a list of all the available keys in the dictionary
Example:
dict = {'Name': 'Zara', 'Age': 7}
print("The keys are:",dict.keys())
5. dict.has_key(key)
The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.
Ex.
dict = {'Name': 'Zara', 'Age': 7}
print "Value :”, dict.has_key('Age')
print "Value :”,dict.has_key('Sex')
6.dict.item()
The items() method returns a view object that displays a list of a given dictionary's (key, value) tuple
pair.The items() method doesn't take any parameters.
For.ex
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())
7.dict.fromkeys()
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax:
dict.fromkeys(seq [ , value] )
For ex.
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'
vowels = dict.fromkeys(keys, value)
print(vowels)
8. update()
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Gender': 'female' }
dict.update(dict2)
print ("The updated value :",dict)
Python supports a concept called “list comprehensions”.It can be used to construct lists in a very
natural,easy way,like a mathematics is used to do.
In python, we can write the expression almost exactly like a mathematics with special cryptic syntax.
For example:
>>> L=[X**2 for x in range (10)]
>>> L
[0,1,4,9,16,25,36,49,64,81]
The above code creates a list of square numbers from 0 to 9.This list can be created using a
simplified expression “X**2 for x in range (10)”.This is basically list comprehension.
The list comprehension is achieved using the tools like map, lambda, reduce and filter
MAP:
The map() function applies the values to every member of the list and returns the result.
The map function takes two arguments .
Syntax: result=map(function,sequence)
Example:
>>>def increment_by_three(x):
return x+3
>>>new_list=list(map(increment_by_three,range(10)))
>>>new_list
OUTPUT:
[3,4,5,6,7,8,9,10,11,12]
Another example: There is a build in function for calculating length of a string and and i.e len().We can pass
this function to map and find the length of every element in the list.
>>> names=[‘Sandip’,’Lucky’,’Mahesh’,’Sachin’]
>>>lengths=list(map(len,names))
>>>lengths
[6,5,6,6]
FILTER:
The filter() function selects some of the elements and filters out others .If we use it wit list
comprehension,it is almost equivalent to the filter build-in. This function takes two arguments.
Syntax: result=filter(function,sequence)
for example:
>>>def even_fun(x):
return x%2= =0
>>>r=filter(even_fun,[1,2,3,4,5])
>>>list(r)
[2,4]
In above example,using filter() function the odd numbers are filtered out and only even numbers are
displayed.
LAMBDA:
The lambda function is a simple inline function that is used to evaluate the expression using the given list
of arguments.
Where the argument_list consists of a comma separated list of arguments and the expression is an arithmetic
expression using these arguments.
Example: >>>sum=lambda x,y:x+y
>>>sum(1,3)
4
REDUCE:
The kind of function that combines sequence of elements into a single value is called reduce function.
This function takes two arguments.
Result=reduce(function,sequence)
The function reduce() had been dropped from core of python when migratin to python 3
Hence for using the reduce function we have to import functools to be capable of using reduce.\
>>>import functools
>>>functools.reduce(lambda x,y:x+y[1,2,3,4])
10
ILLUSTRATIVE PROGRAMS
1.Selection Sort
4. Merge Sort
source = [10,90,30,20]
for i in range(len(source)): def mergeSort(alist):
mini = min(source[i:]) print("Splitting ",alist)
min_index = source[i:].index(mini) if len(alist)>1:
source[i + min_index] = source[i] mid = len(alist)//2
source[i] = mini lefthalf = alist[:mid]
print(source) righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
2.Insertion Sort i=0
def insertionSort(alist): j=0
for index in range(1,len(alist)): k=0
currentvalue = alist[index] while (i < len(lefthalf)) and (j < len(righthalf)):
position = index if lefthalf[i] < righthalf[j]:
while position>0 and alist[position- alist[k]=lefthalf[i]
1]>currentvalue:
i=i+1
alist[position]=alist[position-1]
position = position-1 else:
alist[position]=currentvalue alist[k]=righthalf[j]
j=j+1
alist=[12,34,67,30,82] k=k+1
insertionSort(alist) while i < len(lefthalf):
print(alist) alist[k]=lefthalf[i]
i=i+1
3.Histogram
k=k+1
while j < len(righthalf):
def histogram(s):
d=dict() alist[k]=righthalf[j]
for c in s: j=j+1
if c not in d: k=k+1
d[c]=1 print("Merging ",alist)
else: n = input("Enter the size of the list: ")
d[c]+=1 alist = [30,50,10,70]
return d
mergeSort(alist)
def print_hist(h): print(alist)
for c in h:
print c, h[c]
PART- A (2 Marks)
1. What is a list?(Jan-2018)
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.
4. 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]
12. Write a program in Python to delete first element from a list.
def deleteHead(list): del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]
24. Write python program for swapping two numbers using tuple assignment?
a=10 b=20
a,b=b,a
print(“After swapping a=%d,b=%d”%(a,b))
27. Give a function that can take a value and return the first key mapping to that value in a dictionary.(Jan
2019)
a={‘aa’:2, ”bb”:4}
print(a.keys()[0])
28. How to create a list in python? Illustrate the use of negative indexing of list with example. (May 2019)
List Creation:
days = ['mon', 2]
days=[] days[0]=’mon’ days[1]=2
Negative Indexing:
Example:
>>> print(days[-1])
Output: 2
29. Demonstrate with simple code to draw the histogram in python. (May 2019)
def histogram( items ): Output:
for n in items: **
output = '' times = n ***
while( times > 0 ): ******
output += '*' times = times - 1 print(output)
histogram([2, 3, 6, 5])
30. How will you update list items? Give one example. (Nov / Dec 2019)
Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the
list items
fruit = ["banana","apple","cherry"] print(fruit)
['banana', 'apple', 'cherry'] fruit[0] = "pear"
fruit[-1] = "orange" print(fruit)
['pear', 'apple', 'orange']
31. Can function return tuples? If yes Give examples. (Nov / Dec 2019)
Function can return tuples as return values. def circle_Info(r):
#Return circumference and area and tuple c = 2 * 3.14 * r Output
a = 3.14 * r * r return(c,a) (62.800000000000004, 314.0)
print(circle_Info(10))
UNIT V FILES, MODULES, PACKAGES
Files and exceptions: text files, reading and writing files, format operator; command line arguments, errors
and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age
validation, Marks range validation (0-100).
Opening a file:
This function creates a file object, which would be utilized to call other support methods associates with it.
Modes Description
Open a file for reading only. The file pointer is placed at the beginning of the
r
file. This is default mode.
Open a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is default mode.
Open a file for both read and write. The file pointer is placed at the beginning of
r+
the file.
Open a file for both read and write in binary format. The file pointer is placed at
rb+
the beginning of the file
Open a file for writing only. Overwrite the file if exists. If the files does not
w
exists, creates a new file for writing.
1
Open a file for writing only in binary format. Overwrite the file if exists. If the
wb
files does not exists, creates a new file for writing.
Open a file for both read and write. Overwrite the file if exists. If the files does
w+
not exists, creates a new file for writing and reading.
Open a file for both read and write in binary format. Overwrite the file if exists.
wb+
If the files does not exists, creates a new file for writing and reading.
a Open a file for appending. This file pointer is placed at the end of the file.
Open a file for appending only in binary format. This file pointer is placed at the
ab end of the file, if exists. That is, the file is in the appending mode. If the files
does not exists, creates a new file for writing.
Open a file for appending and reading. This file pointer is placed at the end of
a+
the file, if exists.
Open a file for appending and reading in binary format. This file pointer is placed
ab+
at the end of the file, if exists. It creates a new file for reading and writing.
Example: fn=open(‘D:/ex.txt’,’r’)
Syntax : filevariable.write(“filename”,”mode”)
Example:
f=open(‘D:/ex.txt’,’w’)
f.write(“welcome\n”)
f.write(“thank you”)
f.close()
Syntax:
with open (filename, mode) as variable :
block
Example:
with open (“file.txt”, “r”) as file:
contents=file.read( )
Print(contents)
2
Writelines():
The writelines method put multiple data into the file.
The writelines() method writes any string to an open file.
Syntax: filevariable.writelines(string)
Example.py:
Output:
f=open(‘D:/ex.txt’,’w’)
This is my book
str=‘this is my book\n I found it here’ I found it here
f.writelines(str)
f.close()
Reading a file:
This method helps to just view the content of given input files. To read the content of a file, one must open the
file in reading mode.
Syntax: filevariable=open(‘filename’,’r’)
Methods used in reading a file.
1. read(size)
2. Readline()
3. Readlines()
file.read(size)
This read() specifies the size of data to be read from input files.
If size not mentioned, it reads the entire files and cursor waits in last position of files.
Ex.
f=open(“file100.txt”, ”r”)
print(“The first 5 characters of the file are:\n”, f.read(5))
f.close()
OUTPUT:
3
Readline():
This method is used to read a single line from the input file, till the new line character occur.
It doesn’t takes any argument.
Syntax: f.readline()
ex.
f=open(“file.txt”,”r”)
print(“reading content of the file by realine() method:\n”)
print(f.readline())
f.close()
Readlines():
This method is used to read and display all the line from the input file.
Syntax: f.readlines()
ex.
f=open(“file.txt”,”r”)
print(“reading content of the file by realines() method:\n”)
print(f.readlines())
f.close()
encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that
case, the file uses the system default encoding for converting Unicode strings.
mode: Returns the file access mode used while opening a file.
closed: Returns True if a file is closed. It is a Boolean value indicating the current state of the file object.
newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen.
For files not opened in universal newline read mode, the value of this attribute will be None.
Closing a file:
The close() methods of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done.
Syntax: filevariable.close()
Example.py: Output:
Open(‘input.txt’,’wb’) Name of the file: input.txt
4
Example: Python program to implement all file read operation:
fn=open(‘D:/ex.txt’,’r’)
print(fn.read())
fn.seek(0)
Output:
print(fn.read(4)) Welcome to the world of robotics
print(fn.tell()) Welc
4
fn.seek(0) Welcome to the world of robotics
Welcome to the world of robotics
print(fn.readline()) and automation
fn.seek(0)
print(fn.readlines())
ex.txt:
Welcome to the world of robotics
and automation
FILE METHODS
Methods Description
File.close() Close the file. A closed file cannot be read or write anymore.
Flush the internal buffer, like stdio’s fflush. This may be a no-op on
File.flush()
some file like objects.
Return the integer file description that is used by underlying
File.fileno()
implementation to request I/O operation from os.
File.isatty() Return True if the file is connected to a tty(-like) devices, else False.
Read at most size bytes from files (less if the read hits EOF before
File.read([size])
obtaining size bytes)
Read one entries line from the file. A trailing newline character is kept
File.readline([size])
in the string.
Read until EOF using readline() and return a list containing the lines.
File.readlines([sizehint]) If the optional sizehint of argument is present, instead of reading up to
EOF, whole line totaling approximately sizehint bytes are read.
File.seek(offset[,whence]) Set the files current position.
File.tell() Return the files current position
Truncates the files size. If the optional size argument is present, the file
File.truncate([size])
is truncated to that size.
File.write(str) Writes a string to the files. There is no return value.
Writes a sequence of string to a file. The sequences can be any
File.writelines(sequence)
iterable. Object producing string, typically a list of strings.
File.readable() Return true if file stream can be read from.
File.seekable() Return true if file stream supports random access.
File.writable(0 Return true if file stream can be written to.
5
Tell() and seek():
Tell() method display the current position of cursor from the input files.
Seek() takes an argument and moves the cursor to the specified position which is mentioned as argument.
Syntax: print(f.tell())
print(f.seek())
FORMAT OPERATOR
String formatting is the process of infusing things in the strings dynamically and presenting the strings.
There are four different ways to perform string formatting.
1. Formatting with % operator
2. Formatting with format() string methods.
3. Formatting with string literals, called f-strings.
4. String template class
Example:
print('We all are {}.'.format('equal'))
Output: We all are equal.
The format() method has many advantages over the placeholder method:
We can insert object by using index-based position:
Example: print('{2} {1} {0}'.format('directions','the', 'Read'))
Output: Read the directions.
6
We can reuse the inserted objects to avoid duplication:
Example: print ('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))
Output: The first second was alright, but the second second was tough.
Syntax: {[index]:[width][.precision][type]}
Output:
The value of pi is: 3.14159
The value of pi is: 3.14159
1.Using sys.argv:
The sys module provides functions and variables used to manipulate different parts of the Python runtime
environment. This module provides access to some variables used or maintained by the interpreter and to functions
that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
It is a list of command line arguments.
len (sys.argv) provides the number of command line arguments.
sys.argv[0] is the name of the current Python script.
Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-
line arguments.
# total arguments
n = len (sys.argv)
print ("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
7
# Addition of numbers using argparse module
Sum = 0
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:
8
They are mainly two types of errors:
1. Syntax errors :
The python finds the syntax errors when it parses the source program. Once it finds a syntax error,
the python will exit the program without running anything. Commonly occurring syntax errors are:
(i) Putting a keyword at wrong place.
(ii) Misspelling the keyword
(iii) Incorrect Indentation
(iv) Forgetting symbols such as comma, colon, brackets, quotes
(v) Empty blocks
2. Runtime errors:
If a program is syntactically correct-that is, free of syntax errors it will be executed by the python
interpreter. However, the program may exit unexpectedly during execution if it encounters a runtime error.
The run time errors are not detected while parsing the source program, but will occur due to some logical
mistake.
Eg of runtime error are:
1) Trying to access a file which does not exist.
2) Using an identifier which is not defined.
3) Performing operations of incompatible type elements
4) Division by Zero
Such errors are handled using exception handling.
2 StopIteration If the next() method returns null for an iterator, this exception is raised.
Excluding the StopIteration and SystemExit, this is the base class for all
4 StandardError
Python built-in exceptions.
For all numeric data types, its value is raised whenever a number is
8 ZeroDivisionError
attempted to be divided by zero.
9
10 AttributeError This exception is raised if a variable reference or assigning a value fails.
When the endpoint of the file is approached, and the interpreter didn't
11 EOFError get any input value by raw_input() or input() functions, this exception is
raised.
When the given key is not found in the dictionary to be found in, this
16 KeyError
exception is raised.
All exceptions that arise beyond the Python environment have this base
19 EnvironmentError
class.
If an input or output action fails, like when using the print command or
20 IOError the open() function to access a file that does not exist, this exception is
raised.
22 SyntaxError This exception is raised whenever a syntax error occurs in our program.
This exception is raised when an error that occurred during the program's
27 RuntimeError
execution cannot be classified.
10
Handling an exception
When it raises an exception, it must either handle the exception immediately else it terminates and
quits. The exception handling mechanism uses the try….except…..else blocks.
try: includes suspicious code.
After the try: block, include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
write the suspicious code here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Note:
1. A single try statement can have multiple except statements. This is useful when the try block contains
statements that may throw different types of exceptions.
2. You can also provide a general except clause, which handles any exception.
3. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in
the try: block does not raise an exception.
4. The else-block is a good place for code that does not need the try: block's protection.
Example 1:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Output:
Written content in the file successfully
Example 2:
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
Output:
Error: can't find file or read data
11
The except Clause with No specific Exceptions:
You can also use the except statement with no exceptions defined as follows –
Syntax:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
Example:
try:
n=int(input(“Enter some number”))
except
print(“you have entered wrong data”)
else:
print(“You have entered:”,n)
Output:
Enter some number a
You have entered a wrong data
Enter some number 10
You have entered :10
Note: This kind of a try-except statement catches all the exceptions that occur.
12
The try-finally Clause:
You can use a finally: block along with a try: block. The finally block is a place to put any code that must
execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −
Syntax:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
Output:
Error: can't find file or read data
Raising an Exceptions:
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as
follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback
object used for the exception.
Example:
User-Defined Exceptions:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError.
This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
13
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
MODULES
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use.
Example:
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Example:
# importing module calc.py
import calc
print(calc.add(10, 2))
Output: 12
Output:
4.0
720
Import all Names :
The * symbol used with the from import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *
Example:
from math import *
print(sqrt(16))
print(factorial(6))
Output: 4.0
720
14
Renaming the Python module:
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Example: # importing sqrt() and factorial from the
# module math
import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))
Example:
import math
print(math.sqrt(25))
print(math.pi)
print(math.degrees(2))
print(math.radians(60))
print(math.sin(2))
print(math.cos(0.5))
print(math.tan(0.23))
print(math.factorial(4))
import random
print(random.randint(0, 5)) # printing random integer between 0 and 5
print(random.random()) # print random floating point number between 0 and 1
print(random.random() * 100) # random number between 0 and 100
List = [1, 4, True, 800, "python", 27, "hello"]
print(random.choice(List))
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))
15
Packages
A package is a collection of modules. 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.
16
ILLUSTRATIVE PROGRAM
1. Word Count 2.copy files:
import sys def copyFile(oldFile, newFile):
file=open("/Python27/note.txt","r+") f1 = open(oldFile, "r")
wordcount={} f2 = open(newFile, "w")
for word in file.read().split(): while True:
if word not in wordcount: text = f1.read(50)
wordcount[word] = 1 if text == "":
else: break
wordcount[word] += 1 f2.write(text)
file.close(); f1.close()
print ("%-30s %s " %('Words in the File' , 'Count')) f2.close()
for key in wordcount.keys(): return
print ("%-30s %d " %(key , wordcount[key]))
7.What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an error
message.
Example:
#Dividing by zero creates an exception: print 55/0
ZeroDivisionError: integer division or modulo
17
8.What are the two parts in an error message?
The error message has two parts: the type of error before the colon, and specification about the error after
the colon.
Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
9.What are the error messages that are displayed for the following exceptions?
1. Accessing a non-existent list item
2. Accessing a key that isn’t in the dictionary
3. Trying to open a non-existent file
4. IndexError: list index out of range
5. KeyError: what
6. 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
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.
13.What is a pickle?
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any type of
object to a string suitable for storage in a database and then translate the strings back in to objects.
To store a data structure, dump method is used and to load the data structures that are dumped, load
method is used.
18
17.What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Example:
from Game.Level.start
import select_difficulty
18.Write a Python script to display the current date and time. (Jan-2018)
import datetime
print(“date and time”, datetime.datetime.now())
19.What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py. init .py can be an empty file but it
is often used to perform setup needed for the package(import things, load things into path, etc).
Example :
package/
init .py file.py file2.py file3.py subpackage/
init .py submodule1.py submodule2.py
20.How do you use command line arguments to give input to the program? (or) What is command line
argument? (May 2019) (Nov / Dec 2019)
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.
Example:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
19
25.Find the syntax error in the code given:
while True print(‘Hello World’) (Jan 2019)
In the above given program, colon is missing after the condition. The right way to write the above program is,
while True:
print(‘Hello World’)
26.Categorize the different types errors arises during programming. Interpret the following python code
>>>import os (May 2019)
>>>cwd = os.getcwd()
>>>print cwd
20