It Content Sem 2
It Content Sem 2
Quitting Python
Script Mode
This mode is used to execute Python program written in a file. Such a file is called a script. Scripts can be
saved to disk for future use. Python scripts should have the extension .py, it means that the filename ends
with .py.
For example: helloWorld.py
To execute this file in script mode we simply write python3 helloWorld.py at the command prompt.
If you are running new version of Python, then you need to use print statement with parenthesis as in print ("Hello, IIIT
RK Valley");.However in Python version 2.7, this produces the following result:
Output:
We can use the above mentioned functions in python 2.x, but not on python 3.x. input() in python 3.x always return a
string. Moreover, raw_input() has been deleted from python 3
python2.x python3.x
raw_input() -------------- input()
input() ------------------- eval(input())
We can simply say in python 3.x only use of the input () function to read value from the user and it assigns a string to a
variable. x = input()
The parentheses are empty because, the input function does not require any information to do its job.
Program demonstrates that the input function produces a string value.
Output:
The second line shown in the output is entered by the user, and the program prints the first, third, and fourth lines. After
the program prints the message Please enter some text:, the program’s execution stops and waits for the user to type
some text using the keyboard. The user can type, backspace to make changes, and type some more. The text the user
types is not committed until the user presses the Enter (or return) key. In Python 3.X, input() function produces only
strings, by using conversion functions we can change the type of the input value. Example as int(), str() and float().
Multiple Choice Questions
1) Python is -------
a) Objected Oriented Programming Language b) Powerful Programming Language
b) Powerful scripting Language d) All the above
2) Python is developed by ------------
a) Guido van Rossum. b) Balaguruswami c) James Gosling d) None of the above
3) Which of the following is not a keyword?
a) eval b) assert c) nonlocal d) pass
4) All keywords in Python are in _________
a) lower case b) UPPER CASE c) Capitalized d) None of the mentioned
5) Which of the following is true for variable names in Python?
a) unlimited length b) all private members must have leading and trailing underscores
b) underscore and ampersand are the only two special characters allowed d) none of the mentioned
6) Which of the following translates and executes program code line by line rather than the whole program in one
step?
a) Interpreter b) Translator c) Assembler d) Compiler
7) Which of the following languages uses codes such as MOVE, ADD and SUB?
a) assembly language b) Java c) Fortran d) Machine language
8) What is the output of the following assignment operator? y = 10; x = y += 2; print(x)
a) 12 b) 10 c) Syntax error
9) What is assignment operator?
a) = = b)= c) += d) - =
10) What is a correct Python expression for checking to see if a number stored in a variable x is between 0 and 5?
a) x>0 and <5 b) x>0 or x<5 c) x>0 and x<5
Descriptive Questions
1) Explain about Applications and Features of Python Programming Language?
2) Write short notes on types of operators in python with appropriate examples?
3) Explain about interpreter and compiler?
4) What is a programming language? Explain different types of programming languages?
5) What is a variable?
6) What is assignment statement?
7) What is comment and expression?
8) What is wrong with the following statement that attempts to assign the value ten to variable x? 10 = x
9) In Python can you assign more than one variable in a single statement?
10) What is the difference between the following two strings? ’n’ and’\n’?
11) Explain type of operators
12) What is compound assignment operator? Explain with examples?
13) Difference between ‘/’ and ‘//’
Solved Problems
1) Evaluate the value of z=x+y*z/4%2-1
x=input(“Enter the value of x= ”)
y=input(“Enter the value of y= “)
z=input(“Enter the value of z= “)
a=y*z
b=a/4
c=b%2
t=x+c-1
print(“the value of z=x+y*z/4%2-1 is”,t)
Input: Enter the value of x=2
Enter the value of y=3
Enter the value of z=4
Output: the value of z=x+y*z/4%2-1 is 2
Note: while solving equations follow the BEDMAS or PADMAS Rule
2) Python program to show bitwise operators
a = 10
b=4
# Print bitwise AND operation
print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)
# Print bitwise NOT operation
print("~a =", ~a)
# print bitwise XOR operation
print("a ^ b =", a ^ b)
Output: a&b=0
a | b = 14
~a = -11
a ^ b = 14
Programs to do
1) Write a program to find out the value of 9+3*9/3?
2) Write a program to find out the value of (50-5*6)/4?
3) Write a program to find out the value of 3*3.75/1.5?
4) 45-20+(10?5)%5*3=25 what is the operator in the place of “?” mark?
5) 3*6/22%2+7/2*(3.2-0.7)*2 in this problem which one is evaluated first? finally what is the answer?
6) Write a program to display Arithmetic operations for any two numbers?
7) Python Program to find the average of 3 numbers?
8) Write a python program to find simple and compound interest?
9) Write a program that uses raw_input to prompt a user for their Name and then welcomes them.
10) Write a program to prompt the user for hours and rate per hour to compute gross pay.
11) Write program and also Use the Python interpreter to check your answers.
12) Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and
print out the converted temperature.
13) Write a python program to find type of the value of below expressions
a. 4 > 23
b. 5+=21
c. 2**=3
14) Write a python program to prompts the user for x and y operands and find result for all arithmetic operators.
Unit 2 - Data types, I/O, Types of Errors and Conditional Constructs
Module 1 - Data types, I/O, Types of Errors
A data type is a data storage format that can contain a specific type or range of values. Variables can store data of
different types, and different types can do different things. Python has the following data types built-in by default, in
these categories.
Numeric Type: int, float, complex
Output
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then
it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown
in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Flowchart:- # python program to illustrate If statement
i = 10
if (i> 15):
print ("10 is less than 15")
print ("I am Not in if")
Output:
I am Not in if
2.7.2 if- else: if statement alone tells us that if a condition is true it will execute a block of statements and if the condition
is false it won’t. Here comes the else statement. We can use the else statement with if statement to execute a block of
code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
# Python program to illustrate If else statement
#!/usr/bin/python
i = 20;
if (i< 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is false after call
the statement which is not in block (without spaces).
2.7.3 nested-if: A nested if is if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e, we can place
an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i<20):
# First if statement
if (i< 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
else:
print ("i is greater than 15")
if (i< 12):
print ("i is smaller than 12 too")
Output:
I. i is smaller than 15
II. i is smaller than 12 too
2.7.4 if-elif-else ladder: Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
else:
statement
Example:-
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20
2.8 Short Hand if statement
Whenever there is only a single statement to be executed inside
if block then shorthand if can be used. The statement can be put
on the same line as if statement.
Syntax:
if condition: statement
Example: # Python program to illustrate short hand if i = 10
if i< 15: print("i is less than 15")
Output:
i is less than 15
Short Hand if-else statement: This can be used to write the if-
else statements in a single line where there is only one statement
to be executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
Example: # Python program to illustrate short hand if-else i = 10
print(True) if i< 15 else print(False)
Output:
True
Multiple Choice Questions
1) Which statement is correct?
a) List is immutable && Tuple is mutable b) List is mutable && Tuple is immutable
b) Both are Mutable. d) Both are Immutable.
2) Which one of the following is mutable data type?
a) Set b) Int c) Str d) tupl
3) Which one of the following is immutable data type?
a) List b) Set c) Int d) dict
4) Which of these is not a core data type?
a) List b) Tuple c) Dictionary d) Class
5) Which one of the following is False regarding data types in Python?
a) In python, explicit data type conversion is possible
b) Mutable data types are those that can be changed.
c) Immutable data types are those that cannot be changed.
d) None of the above
6) Which of the following function is used to know the data type of a variable in Python?
a) datatype() b) typeof() c) type() d) vartype()
7) Which one of the following is a valid Python if statement :
a) if (a>=2): b) if (a >= 2) c) if (a => 22) d) if a >= 22
8) What keyword would you use to add an alternative condition to an if statement?
a) else if b) elseif c) elif d) None of the above
9) Can we write if/else into one line in python?
a) Yes b) No c) if/else not used in python d) None of the above
10) Which statement will check if a equal to b?
a) if a = b: b) if a == b: c) if a === c: d)if a == b
Solved Problem Set
1) Write a Python program to find whether the given number is divisible by 7 and multiple of 5?
num=int(input("Enter a number: "))
if num%7==0 and num%5==0:
print(num, "is divisible by 7 and multiple of 5")
else:
print("the given number is either divisible by 7 or multiple of 5")
2) Write a program to input any number and check whether it is even or odd
num=int(input("Enter a number: "))
if num%2==0:
print("Even number")
else:
print("Odd number")
3) Write a program to input any number and check whether it is negative, positive or zero
num=int(input("Enter a number: "))
if num>0:
print("Positive number")
else if num<=0:
print("Negative number")
else:
print("Zero")
4) A student will not be allowed to sit in exam if his/her attendance is less than 75%.
Take following input from user:
Number of classes held
Number of classes attended.
And print
percentage of class attended
Is student is allowed to sit in exam or not.
print "Number of classes held"
noh = input()
print "Number of classes attended"
noa = input()
atten = (noa/float(noh))*100
print "Attendence is",atten
ifatten>= 75:
print "You are allowed to sit in exam"
else:
print "Sorry, you are not allowed. Attend more classes from next time."
Programs to do
1) Take values of length and breadth of a rectangle from user and check if it is square or not.
2) Take two int values from user and print greatest among them
3) A shop will give discount of 10%, if the cost of purchased quantity is more than 1000.
Ask user for quantity, suppose, one unit will cost 100.
Ex: quantity=11, cost=11*100=1100>1000, so, he will get 10% discount, that is 110,
Final cost is 1100-110=990
4) A company decided to give bonus of 5% to employee if his/her year of service is more than 5 years.
Ask user for their salary and year of service and print the net bonus amount.
5) A school has following rules for grading system:
a. Below 25 – F d. 50 to 60 – C
b. 25 to 45 – E e. 60 to 80 – B
c. 45 to 50 – D f. Above 80 – A
Ask user to enter marks and print the corresponding grade.
6) Take input of age of 3 people by user and determine oldest and youngest among them.
7) Write a program to print absolute value of a number entered by user.
E.g.- INPUT: 1 OUTPUT: 1, INPUT: -1 OUTPUT: 1
8) Modify the 4th question (in solved problem set) to allow student to sit if he/she has medical cause. Ask user if
he/she has medical cause or not ('Y' or 'N') and print accordingly.
9) Ask user to enter age, sex (M or F ), marital status ( Y or N ) and then using following rules print their place
of service. if employee is female, then she will work only in urban areas.
if employee is a male and age is in between 20 to 40 then he may work in anywhere
if employee is male and age is in between 40 t0 60 then he will work in urban areas only.
And any other input of age should print "ERROR".
Descriptive Questions
1) What is data type? What are the different types of data?
2) What are the numeric data types? Explain with examples.
3) What are the sequence types of data?
4) Explain about type conversions.
5) What is mutable and immutable? What are mutable and immutable data types?
6) Explain about python output formatting.
7) Describe types of errors.
8) Explain about types of conditional constructs.
9) Give examples for all conditional constructs.
10) Write shorthand if and shorthand if-else statement.
Unit 3 – Loops Control Statements and Functions
Module 1 – While Loop
Introduction
Looping is a powerful programming technique through which a group of statements is executed repeatedly, until
certain specified condition is satisfied. Looping is also called repetitive or iterative control statements.
A loop in a program essentially consists of two parts, one is called the body of the loop and other is known as a control
statement. The control statement performs a logical test whose result is either True or False. If the result of this
logical test is true, then the statements contained in the body of the loop are executed. Otherwise, the loop is
terminated.
There must be a proper logical test condition in the control statement, so that the statements are executed repeatedly
and the loop terminates gracefully. If the logical test condition is carelessly designed, then there may be possibility of
formation of an infinite loop which keeps executing the statements over and over again.
3.1 while loop
This is used to execute a set of statements repeatedly as long as the specified condition is true. It is an indefinite loop.
In the while loop, the condition is tested before executing body of the statements. If the condition is True, only body
of the block of statements will be executed otherwise if the condition is False, the control will jump to other
statements which are outside of the while loop block.
Syntax:
while(logexp):
block of Statements
Where,
while is a keyword
logexp is a logical expression that results in either True or Fasle
Statement may be simple or a compound statement
Here, first of all the logical expressions is evaluated and if the result is true (non-zero) then the statement is repeatedly
executed. If the result is false (zero), then control comes out of the loop and continues with the next executable
statements.
Flowchart:
In while loop there are mainly it contains three parts, which are as follows
Initialization: to set the initial value for the loop counter. The loop counter may be an increment counter or a
decrement counter
Decision: an appropriate test condition to determine whether the loop be executed or not
Updation: incrementing or decrementing the counter value.
Example Programs:
Q1. Write a program to display your name up to ‘n’ times
Output:
Q2. Write a program to display natural numbers up to n
Output:
Q3.Write a program to display even numbers up to n
Output:
3.1.1 The infinite while loop: A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This
results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client
programs can communicate with it as and when required.
Program to demonstrate infinite loop:
Above two programs that never stop, that executes until your Keyboard Interrupts (ctrl+c). Otherwise, it would have
gone on unendingly. Many ‘Hi’ output lines will display when you executes above two programs and that never
display ‘Good bye’
3.1.2 While loop with else clause/statement: Python allows an optional else clause at the end of a while loop. This is
a unique feature of Python. If the else statement is used with a while loop, the else statement is executed when the
condition becomes false. But, the while loop can be terminated with a break statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is False
Syntax:
Example Program:
Q1. Write a program to demonstrate while loop with else block.
Output:
Q2. Write a program to demonstrate else block with break statement
Output:
Module 2 – For Loop
3.2 for loop
Like the while loop, for loop works, to repeat statements until certain condition is True. The for loop in python is used
to iterate over a sequence (list, tuple, string and range () function) or other iterable types. Iterating over a s sequence is
called traversal. Here, by sequence we mean just an ordered collection of items. for loop is usually known as definite
loop because the programmer knows exactly how many times the loop will repeat.
Syntax:
for counter_variable in sequence:
block of statements
Here counter_variable is the variable name that takes the value of the item inside the sequence on each iteration. Loop
continues until we reach the last item in the sequence. The body of for the loop is separated from the rest of the code
using indentation.
Example programs:
Q1. Write a program to make sum of all numbers stored in a list.
Output :
Output:
Q3. If you want to display including the given input number you can
write a program like
Output:
3.2.2 for loop with else:
A for loop can have an optional else block. The else part is executed when the loop has exhausted iterating the list.
But, when the break statement use in for loop, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Q1. Program to demonstrate else block in for loop
Output:
Here, the for loop prints numbers from the starting number to less than ending number. When the for loop exhausts, it
executes the block of code in the else and prints No items left.
Q2. Program to demonstrate else block in for loop with break statement:
Output:
Note:
You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or
vice versa.
Example Program: Program to demonstrate nested for loop Nested while loop:
Output:
while loop
Output:
Example Programs:
Write a program to demonstrate continue statement by using for loop
Output:
In output, 5 integer value is skipped based on if condition and continues flow of the loop until the condition satisfied.
3.4.3 Pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute. It is a null statement. However, nothing happens when the pass statement is
executed. It results in no operation (NOP). Pass statement can also be used for writing empty loops, functions and
classes.
Syntax: pass
Example Program:
Program to demonstrate pass statement using for loop
Output:
Solved Questions
1) Write a program to display your name up to n times.
Using while loop Output:
a) The program will loop indefinitely b) The value of number will be printed exactly 1 time
b) The while loop will never get executed d) The value of number will be printed exactly 5 times
7) Which of the following sequences would be generated by given line of the code?
a) 5 4 3 2 1 0 -1 b) 5 4 3 2 1 0 c)5 3 1 d) Error
8) Which of the following is a valid for loop in Python?
a) for (i=0;i<=n; i++) b) for i in range(5) c) for i in range (1, 5): d) for i in range(0,5,1)
9) Which statement is used to terminate the execution of the nearest enclosing loop in which it appears?
a) pass b) break c) continue d) jump
10) Which statement indicates a NOP?
a) Pass b) break c) continue d) jump
Module 3- Built-In Functions and User defined functions
A function is a named sequence of statement(s) that performs a computation. It contains line of code(s) that are
executed sequentially from top to bottom by Python interpreter. They are the most important building blocks for any
software in Python. Functions can be categorized as belonging to
1) Modules
2) Built in Functions
3) User Defined Functions
Module:
A module is a file containing Python definitions (i.e. functions) and statements. Standard library of Python is extended
as module(s) to a programmer. Definitions from the module can be used within the code of a program. To use these
modules in the program, a programmer needs to import the module. Once you import a module, you can reference
(use), any of its functions or variables in your code. There are many ways to import a module in your program, the
one‟s which you should know are:
1) import
2) from
Import
It is simplest and most common way to use modules in our code.
Syntax: import modulename1 [,modulename2, ---------]
Ex: >>> import math
On execution of this statement, Python will
(i) search for the file „math.py‟.
(ii) Create space where modules definition & variable will be created,
(iii) then execute the statements in the module.
Now the definitions of the module will become part of the code in which the module was imported.
To use/ access/invoke a function, you will specify the module name and name of the function- separated by dot (.).
This format is also known as dot notation
>>> value= math.sqrt (25) # dot notation
The example uses sqrt( ) function of module math to calculate square root of the value provided in parenthesis, and
returns the result which is inserted in the value. The expression (variable) written in parenthesis is known as argument
(actual argument). It is common to say that the function takes arguments and return the result. This statement invokes
the sqrt ( ) function.
From Statement
It is used to get a specific function in the code instead of the complete module file. If we know beforehand which
function(s), we will be needing, then we may use from. For modules having large no. of functions, it is recommended
to use from instead of import.
Syntax: >>> from modulename import functionname [, functionname…..]
Ex >>> from math import sqrt
value = sqrt (25)
Here, we are importing sqrt function only, instead of the complete math module. Now sqrt( ) function will be directly
referenced to. These two statements are equivalent to previous example.
from modulename import *
will import everything from the file.
Note: You normally put all import statement(s) at the beginning of the Python file but technically they can be
anywhere in program.
Lets explore some more functions available in math module:
ceil( x ):
It returns the smallest integer not less than x, where x is a numericexpression.
>> math.ceil(-45.17)
-45.0
>> math.ceil(100.12)
101.0
>> math.ceil(100.72)
101.0
floor( x ) :
It returns the largest integer not greater than x, where x is a numeric expression.
>> math.floor(-45.17)
-46.0
>> math.floor(100.12)
100.0
>> math.floor(100.72)
100.0
fabs( x ):
It returns the absolute value of x, where x is a numeric value.
>> math.fabs(-45.17)
45.17
>> math.fabs(100.12)
100.12
>> math.fabs(100.72)
100.72
exp( x ) :
It returns exponential of x:ex, where x is a numeric expression.
>> math.exp(-45.17)
2.41500621326e-20
>> math.exp(100.12)
3.03084361407e+43
>> math.exp(100.72)
5.52255713025e+43
log( x ):
It returns natural logarithm of x, for x > 0, where x is a numeric expression.
>> math.log(100.12)
4.60636946656
>> math.log(100.72)
4.61234438974
log10( x ):
It returns base-10 logarithm of x for x > 0, where x is a numeric expression.
>> math.log10(100.12)
2.00052084094
>> math.log10(100.72)
2.0031157171
pow( x, y ):
It returns the value of xy, where x and y are numeric expressions.
>> math.pow(100, 2)
10000.0
>> math.pow(100, -2)
0.0001
>> math.pow(2, 4)
16.0
>> math.pow(3, 0)
1.0
sqrt (x ):
It returns the square root of x for x > 0, where x is a numeric expression.
>> math.sqrt(100)
10.0
>> math.sqrt(7)
2.64575131106
cos (x):
It returns the cosine of x in radians, where x is a numeric expression
>> math.cos(3)
-0.9899924966
>> math.cos(-3)
-0.9899924966
>> math.cos(math.pi)
-1.0
sin (x):
It returns the sine of x, in radians, where x must be a numeric value.
>> math.sin(3)
0.14112000806
>> math.sin(-3)
-0.14112000806
>> math.sin(0)
0.0
tan (x):
It returns the tangent of x in radians, where x must be a numeric value.
>> math.tan(3)
-0.142546543074
>> math.tan(-3)
0.142546543074
>> math.tan(0)
0.0
degrees (x):
It converts angle x from radians to degrees, where x must be a numeric value.
>> math.degrees(3)
171.887338539
>> math.degrees(-3)
-171.887338539
>> math.degrees(0)
0.0
radians(x):
It converts angle x from degrees to radians, where x must be a numeric value.
>> math.radians(3)
0.0523598775598
>> math.radians(-3)
-0.0523598775598
Some functions from random module are:
random ( ):
It returns a random float x, such that 0 ≤ x<1
>>>random.random ( )
0.281954791393
>>>random.random ( )
0.309090465205
randint (a, b):
It returns a int x between a & b such that a ≤ x ≤ b
>>> random.randint (1,10)
5
>>> random.randint (-2,20)
-1
uniform (a,b):
It returns a floating point number x, such that a <= x < b
>>> random.uniform (5,10)
5.52615217015
randrange ([start,] stop [,step]):
It returns a random item from the given range
>>> random.randrange(100,1000,3)
150
Built in Function:
Built in functions are the function(s) that are built into Python and can be accessed by a Programmer. These are
always available and for using them, we don‟t have to import any module (file). Python has a small set of built-in
functions as most of the functions have been partitioned to modules. This was done to keep core language precise.
abs (x): It returns distance between x and zero, where x is a numeric expression.
>>> abs(-45)
45
>>> abs(119L)
119
max( x, y, z, .... ): It returns the largest of its arguments: where x, y and z are numeric variable/expression.
>>> max(80, 100, 1000)
1000
>>> max(-80, -20, -10)
-10
min( x, y, z, .... ): It returns the smallest of its arguments; where x, y, and z are numeric
variable/expression.
>>> min(80, 100, 1000)
80
>>> min(-80, -20, -10)
-80
cmp( x, y ): It returns the sign of the difference of two numbers: -1 if x < y
0 if x == y
1 if x > y
where x and y are numeric variable/expression.
>>> cmp(80, 100) -1
>>> cmp(180, 100) 1
divmod (x,y ): Returns both quotient and remainder by division through a tuple, when x is divided by y; where x & y
are variable/expression.
>>> divmod (14,5) (2,4)
>>> divmod (2.7, 1.5)
(1.0, 1.20000)
len (s): Return the length (the number of items) of an object. The argument may
be a sequence (string, tuple or list) or a mapping (dictionary).
>>> a= [1,2,3]
>>> len (a)
3
>>> b= “Hello‟
>>> len (b)
5
range (start, stop[, step]): This is a versatile function to create lists containing arithmetic progressions. It is most often
used in for loops. The arguments must be plain integers.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8,-9]
>>> range(0)
[]
>>> range(1, 0)
[]
round( x [, n] ): It returns float x rounded to n digits from the decimal point, where x and n are numeric expressions.
If n is not provided then x is rounded to 0 decimal digits.
>>> round(80.23456, 2)
80.23
>>> round(-100.000056, 3)
-100.0
>>> round (80.23456)
80.0
Composition
Composition is an art of combining simple function(s) to build more complicated ones, i.e., result of one function is
used as the input to another.
Example
Suppose we have two functions fn1 & fn2, such that
a= fn2 (x)
b= fn1 (a)
then call to the two functions can be combined as
b= fn1 (fn2 (x))
Similarly, we can have statement composed of more than two functions. In that result of one function is passed as
argument to next and result of the last one is the final result.
Ex
>>> math.exp (math.log (a+1))
Ex
>>> degrees=270
>>> math.sin (degrees/360.0 *2*math.pi)
Composition is used to package the code into modules, which may be used in many different unrelated places and
situations. Also it is easy to maintain the code.
User Defined Functions
So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself
(built in), but it is also possible for programmer to write their own function(s). These functions can then be combined
to form a module which can then be used in other programs by importing them. To define a function keyword def is
used. After the keyword comes an identifier i.e. name of the function, followed by parenthesized list of parameters and
the colon which ends up the line. Next follows the block of statement(s) that are the part of function.
Before learning about Function header & its body, let’s explore block of statements, which become part of function
body
Block of statements
A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while
executing. In Python, statements in a block are written with indentation. Usually, a block begins when a line is
indented (by four spaces) and all the statements of the block should be at same indent level. A block within block
begins when its first statement is indented by four space, i.e., in total eight spaces. To end a block, write the next
statement with the same indentation before the block started
Syntax:
def fun_name (PARAMETER1, PARAMETER2, …..): #Square brackets include
statement(s) #optional part of statement
Let’s write a function to greet the world:
def sayHello (): # Line No. 1
print (“Hello World!”) # Line No.2
The first line of function definition, i.e., Line No. 1 is called header and the rest, i.e.
Line No. 2 in our example is known as body. Name of the function is sayHello, and empty parenthesis indicates no
parameters. Body of the function contains one Python statement, which displays a string constant on screen.
Function Header
It begins with the keyword def and ends with colon and contains the function identification details. As it ends with
colon, we can say that what follows next is, block of statements.
Function Body
Consisting of sequence of indented (4 space) Python statement(s), to perform a task. Defining a function will create a
variable with same name, but does not generate any result. The body of the function gets executed only when the
function is called/invoked. Function call contains the name of the function (being executed) followed by the list of
values (i.e. arguments) in parenthesis
Ex:
def sayHello (): # Function Definition
print (“Hello World!”) # Block of Statements
sayHello () # Call/invoke statement of this function
O/P:
Hello World!
Apart from this, you have already seen many examples of invoking of functions in Modules & Built-in Functions.
Let‟s know more about def. It is an executable statement. At the time of execution a function is created and a name
(name of the function) is assigned to it. Because it is a statement, def can appear anywhere in the program. It can even
be nested
if condition:
def fun ( ): # function definition one way
else:
def fun ( ): # function definition other way
fun ( ) # calls the function selected.
This way we can provide an alternative definition to the function. This is possible because def is evaluated when it is
reached and executed.
Let’s explore Function body
The first statement of the function body can optionally be a string constant, docstring, enclosed in triple quotes. It
contains the essential information that someone might need about the function, such as
What function does (without How it does) i.e. summary of its purpose
Type of parameters it takes
Effect of parameter on behavior of functions, etc.
DocString is an important tool to document the program better, and makes it easier to understand. We can actually
access docstring of a function using __ doc__ (function name). Also, when you used help (), then Python will provide
you with docstring of that function on screen. So it is strongly recommended to use docstring … when you write
functions
Function is pretty simple and its objective is pretty much clear from the docString added to the body.
The last statement of the function, i.e. return statement returns a value from the function. Return statement may
contain a constant/literal, variable, expression or function, if return is used without anything, it will return None. In
our example value of a variable area is returned.
Instead of writing two statements in the function, i.e.
a = radius **2
return a
We could have written return radius **2
Here the function will first calculate and then return the value of the expression. It is possible that a function might not
return a value, as sayHello( ) was not returning a value. sayHello( ) prints a message on screen and does not contain a
return statement, such functions are called void functions.Void functions might display something on the screen or
have some other effect, but they don‟t have a return value. If you try to assign the result of such function to a variable,
you get a special value called None.
Parameters and Arguments
Parameters are the value(s) provided in the parenthesis when we write function header. These are the values required
by function to work. Let’s understand this with the help of function written for calculating area of circle.
radius is a parameter to function area. If there is more than one value required by the function to work on, then, all of
them will be listed in parameter list separated by comma.
Arguments are the value(s) provided in function call/invoke statement. List of arguments should be supplied in same
way as parameters are listed. Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
Scope of Variables
Scope of variable refers to the part of the program, where it is visible, i.e., area where you can refer (use) it. We can
say that scope holds the current set of variables and their values. We will study two types of scope of variables- global
scope or local scope.
Global Scope
A variable, with global scope can be used anywhere in the program. It can be created by defining a variable outside
the scope of any function/block.
Output:
e
p
p
4.4 Change or add elements to a list
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:
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When
the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers [1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each
index “maps to” one of the elements.
List indices work the same way as string indices:
4.5 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:
cheeses = ['Cheddar', 'Edam', 'Gouda']
for cheese in cheeses:
print (cheese)
This works well if you only need to read the elements of the list. But if you want to write or update the elements, you
need the indices. A common way to do that is to combine the functions range and len:
numbers = [17, 123]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element.len returns the number of elements in the list. range returns a list
of indices from 0 to n−1, where n is the length of the list. Each time through the loop, i gets the index of the next
element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:
for x in empty:
print ('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
4.6 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]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
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 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.
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']
Syntax: List[start:end:step]
start –starting point of the index value end
stop –ending point of the index value
step- increment of the index values
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3:1]
['b', 'c']
Module 2 - List methods
4.7 - Adding Elements into a list
4.7.1 list.append()
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']
4.7.2 list.extend()
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']
4.7.3 list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert,
so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Example 1: Inserting an Element to the List
# vowel list
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3
# the position of 'o' will be 4th
vowel.insert(3, 'o')
print('Updated List:', vowel)
Deleting elements
4.7.4 list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
4.7.5 list.clear()
Remove all items from the list. Equivalent to del a[:].
Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
4.7.6 list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the
last item in the list. (The square brackets around the I in the method signature denote that the parameter is optional, not
that you should type square brackets at that position. You will see this notation frequently in the Python Library
Reference.)
>>> t = [‘a’, ‘b’, ‘c’]
>>> x = t.pop(1)
>>> print (t)
[‘a’, ‘c’]
>>> print (x)
b
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’]
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> del t[1:5]
>>> print (t)
[‘a’, ‘f’]
As usual, the slice selects all the elements up to, but not including, the second index.
4.7.6 list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such
item. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a
particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather
than the start argument.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Example: Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
4.7.7 list.count(x)
Return the number of times x appears in the list.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
4.7.8 list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Most list methods are void; they modify the list and return None. If you accidentally write list= list.sort(), you will be
disappointed with the result.
Example: Sort a given list
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
Example : Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
4.7.9 list.reverse()
Reverse the elements of the list in place.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
4.7.10 list.copy()
Return a shallow copy of the list. Equivalent to a[:]
# mixed list
my_list = ['cat', 0, 6.7]
# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
4.8 List Comprehension
List comprehension is an elegant and concise way to create a new list from an existing list in Python. A list
comprehension consists of an expression followed by for statement inside square brackets. Here is an example to
make a list with each item being increasing power of 2.
Module 3 – Tuples
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two
examples of sequence data types (Sequence Types — list, tuple, range). Since Python is an evolving language, other
sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they
may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple
is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to
create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples
are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing
(or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and
are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to
accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is
constructed by following a value with a comma. For example:
A tuple can also be created without using parentheses. This is known as tuple packing.
4.10 Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
Indexing:
We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 6
elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range (6,7,... in this
example) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
Negative Indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing:
We can access a range of items in a tuple by using the slicing operator colon:.
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need the index that will slice the portion from the tuple.
4.11 Changing a Tuple
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once they have been
assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a
tuple. Deleting a tuple entirely, however, is possible using the keyword del.
Output:
Example 1
Output:
Example: 2
Output:
We cannot delete or remove characters from string,deleting the string is possible use the keyword del.
Comparing Strings: Python allows you to compare strings using relational (or comparison) operator such as
= =,! =, >, <, < =, >=, etc.
== if two strings are equal, it returns True
!= or <> if two strings are not equal, it returns True
if first string is greater than the second, it returns True
< if second string is greater than the first ,it returns True
>= if first string is greater than or equal to the second, it returns True
<= if second string is greater than or equal to the first, it returns True
Note:
These operators compare the strings by using the lexicographical order i.e using ASCII values of the
characters.
The ASCII values of A-Z is 65 -90 and ASCII code for a-z is 97-122 .
Logical Operators on String in Python: Python considers empty strings as having boolean value of ‘false’ and non-
empty string as having boolean value of ‘true’.
Let us consider the two strings namely str1 and str2 and try boolean operators on them:
Output:
Example:
Example:
Example:
Python program to print reverse string using for loop
The method center() makes str centered by taking width parameter into account. Padding is specified by parameter
fillchar. Default filler is a space.
Syntax: str.center(width[, fillchar])
The function max() returns the max character from string str according to ASCII value.in first print statement y is
max character, because ASCII code of "y" is 121. In second print statement "s" is max character, ASCII code of "s" is
115.
Syntax: max(str)
The function min() returns the min character from string str according to ASCII value.
Syntax: min(str)
endswith(“string”, beg, end): This function returns true if the string ends with mentioned string(suffix) else return
false.Return Bool Value
The use of start and end to generate slice of Python string str.
Syntax: str.endswith(suffix[, start[, end]])
startswith(“string”, beg, end):This function returns true if the string begins with mentioned string(prefix) else return
false.
find(“string”, beg, end):This function is used to find the position of the substring within a string. It takes 3
arguments, substring , starting index(by default 0) and ending index(by default string length).
o It returns “-1” if string is not found in given range.
o It returns first occurrence of string if found.
Return the lowest index in S where substring sub is found
If given Python string is found, then the find() method returns its index. If Python string is not found then -1 would be
returned.
Syntax : str.find(str, beg=0 end=len(string))
rfind(“string”, beg, end): This function is similar to find(), but it returns the position of the last occurrence of sub
string.
replace(): This function is used to replace the substring with a new substring in the string. This function has 3
arguments. The string to replace, new string which would replace and max value denoting the limit to replace action
(by default unlimited).
The method isalnum() is used to determine whether the Python string consists of alphanumeric characters, false
otherwise. Syntax:str.isalnum()
The method isalpha() return true if the Python string contains only alphabetic character(s), false otherwise.
Syntax: str.isalpha()
The method isdigit() return true if the Python string contains only digit(s),false otherwise.
Syntax: str.isdigit()
The method islower() return true if the Python string contains only lower cased character(s), false otherwise
Syntax: str.isdigit()
The method isspace() return true if the Python string contains only white space(s).
Syntax: str.isspace()
The method istitle() return true if the string is a titlecased
Syntax: str.istitle()
The method isupper() return true if the string ontains only upper cased character(s), false otherwise.
Sytax: str.isupper()
The method ljust(), it returns the string left justified. Total length of string is defined in first parameter of method
width. Padding is done as defined in second parameter fillchar .( default is space)
Syntax:-str.ljust(width[, fillchar])
In above example you can see that if you don't define the fillchar then the method ljust() automatically take space as
fillchar.
The method rjust(), it returns the string right justified. Total length of string is defined in first parameter of
methodwidth. Padding is done as defined in second parameter fillchar .( default is space)
Syntax: str.rjust(width[, fillchar])
This function capitalize() first letter of string.
Syntax: str.capitalize()
The method lower() returns a copy of the string in which all case-based characters have been converted to lower
case. Syntax: str.lower()
The method upper() returns a copy of the string in which all case-based characters have been converted to upper case.
Syntax: str.upper()
The method title() returns a copy of the string in which first character of all words of string are capitalised.
Syntax: str.title()
The method swapcase() returns a copy of the string in which all cased based character swap their case
Syntax: str.swapcase()
This method join() returns a string which is the concatenation of given sequence and stringas shown in example.
seq = it contains the sequence of separated strings.
str = it is the string which is used to replace the separator of sequence
Syntax: str.join(seq)
The method lstrip() returns a copy of the string in which specified char(s) have been stripped from left side of string.
If char is not specified then space is taken as default.
Syntax: str.lstrip([chars])
The method rstrip() returns a copy of the string in which specified char(s) have been stripped from right side of
string. If char is not specified then space is taken as default.
Syntax: str.rstrip([chars])
The method strip() returns a copy of the string in which specified char(s) have been stripped from both side of string.
If char is not specified then space is taken as default.
Syntax: str.strip([chars])
The method split() returns a list of all words in the string, delimiter separates the words. If delimiter is not specified
then whitespace is taken as delimiter, parameter num
Syntax: str.split("delimiter", num)
Multiple Choice Questions
1) What will be the output of above Python code?
a) 1 b) 6/4 c) 1.5 d) str1
2) What will be the output of below Python code?
a) format B. formation C. orma D. ormat
3) What will be the output of below Python code?
a) Application b) Application c) ApplicAtion d) Application
4) What will be the output of below Python code?
a) POWER b) Power c) power d) power
5) What will the below Python code will return?
a) 70251 b) 7 c) 15 d) Error
6) Which of the following will give "Simon" as output?
3) Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the
string length is less than 2, return instead of the empty string.
Programs to DO
1) Write a program to find number of digits, alphabets and symbols?
2) Write a program to convert lower case to upper case from given string?
3) Write a program to print the following output? image like
4) Write a program to check whether given string is palindrome or not?
5) Write a program to find no_ words, no_letters, no_digits and no_blanks in a line?
6) Write a program to sort list names in alphabetical order?
7) To find the first character from given string,count the number of times repeated and replaced with * except
first character then print final string?
8) To find the strings in a list which are matched with first character equals to last character in a string?
9) Write a program that accepts a string from user and redisplays the same string after removing vowels from it?
10) This is a Python Program to take in two strings and display the larger string without using built-in functions?
11) Python Program to Read a List of Words and Return the Length of the Longest One?
12) Python Program to Calculate the Number of Upper-Case Letters and Lower-Case Letters in a String?
Module 3 - Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the
indices 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 map 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 map 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 curly 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 weprint the dictionary again, we see a key-
value pair with a colon between the keyand value:
>>> print (eng2sp)
{'one': 'uno'}
This output format is also an input format. For example, you can create a newdictionary 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'
5.7 Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside
square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand,
the get() method returns None if the key is not found.
Output:
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using
the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
Example:1
Example:2
Example:3
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. 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.
try block with multiple except statements:
try:
You do your operations here;
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
The else clause:
The try ... except block can optionally have an else clause, which, when present, must follow all except blocks. The
statement(s) in the else block is executed only if the try clause does not raise an exception.
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:
Syntax:
try:
You do your operations here;
Due to any exception, this may be skipped.
finally:
This would always be executed.
Example:
User Defined Exceptions:
Python has many built-in exceptions. If we want to create user-defined exception, we need to use Exception class.
Programs may name their own exceptions by creating a new exception class.
class UnderAge(Exception):
pass
def verify_age(age):
if int(age) < 18:
raise UnderAge
else:
print('Age: '+str(age))
verify_age(23) # won't raise exception
verify_age(17) # will raise exception
Example
Output:
a) 1 b) 2 c) 3 d) error, there is more than one return statement in a single try-finally block
5) What is the output of the following code?
1 r (or) rt Opens a text file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
2 r+ Opens a text file for both reading and writing. The file pointer placed at the beginning of
(or)rt+ the file.
3 rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
4 rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
5 w (or) Opens a text file for writing only. Overwrites the file if the file exists. If the file does not
wt exist, creates a new file for writing.
6 w+ (or) Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
wt+ the file does not exist, creates a new file for reading and writing.
7 wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
8 wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
9 a (or) Opens a text file for appending. The file pointer is at the end of the file if the file exists.
at That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
10 a+ (or) Opens a text file for both appending and reading. The file pointer is at the end of the file if
at+ the file exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.
11 ab Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.
12 ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
13 x Opens a file for exclusive creation. If the file already exists, the operation fails.
Module 3 – File Handling Methods
File methods: A file object contains the methods for reading and writing data are as follows
read([number.int): str ---> Returns the specified number of characters from the file. If the argument is omitted,
the entire remaining contents in the file are read.
readline(): str ----> Returns the next line of the file as a string
readlines(): list ----> Returns a list of the remaining lines in the file.
write(s: str): None ---> Writes the string to the file.
close(): None ---> Closes the file
write(str): Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in
the file until the flush() or close() method is called.
writelines(sequence): Write a sequence of strings to the file. The sequence can be any iterable object producing
strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines()
does not add line separators.) After a file is opened for writing data, you can use the write method to write a string to
the file
Here is writing demo into files
The program opens a file named student.txt using the w mode for writing data (line 3). If the file does not exist, the
open function creates a new file. If the file already exists, the contents of the file will be overwritten with new data.
You can now write data to the file. When a file is opened for writing or reading, a special marker called a file pointer
is positioned internally in the file. A read or write operation takes place at the pointer‘s location. When a file is
opened, the file pointer is set at the beginning of the file. When you read or write data to the file, the file pointer
moves forward
Testing a File’s Existence:
To prevent the data in an existing file from being erased by accident, you should test to see if the file exists before
opening it for writing. The isfile function in the os.path module can be used to determine whether a file exists.
Testing a File‘s Existence Code:
Here isfile("students.txt.txt") returns True if the file students.txt exists in the current directory.
Reading Data:
After a file is opened for reading data, you can use the read method to read a specified number of characters or all
characters from the file and return them as a string, the readline() method to read the next line, and the readlines()
method to read all the lines into a list of strings.
Reading Data demo code:
OUTPUT:
Reading all data from file
Programs often need to read all data from a file. Here are two common approaches to accomplishing this task:
1. Use the read() method to read all data from the file and return it as one string.
2. Use the readlines() method to read all data and return it as a list of strings.
These two approaches are simple and appropriate for small files, but what happens if the file is so large that its
contents cannot be stored in the memory? You can write the following loop to read one line at a time, process it, and
continue reading the next line until it reaches the end of the file
Using while loop Using for loop
To write numbers to a file, you must first convert them into strings and then use the write method to write them to the
file. In order to read the numbers back correctly, separate them with whitespace characters, such as " " or \n.
Closing file:
When you ‘re done working, you can use the file.close() command to end things. What this does is close the file
completely, terminating resources in use, in turn freeing them up for the system to deploy elsewhere. It‘s important to
understand that when you use the file.close() method, any further attempts to use the file object will fail.
Syntax: fileobject.close()
Programs to do
1) How do you open a file for reading, for writing, and for appending, respectively?
2) How do you determine whether a file exists?
3) What method do you use to read all data into a string?
4) What method do you use to read a line?
5) What method do you use to read all lines into a list?
6) When reading data, how do you know if it is the end of the file?
7) What function do you use to write data to a file?
8) How do you write and read numeric data?
Multiple Choice Questions
1) Which function is used to write a sequence of strings to the file?
a) Writeline() b) read lines() c) Writelines() d) readline()
2) What is the meaning of 'a' mode?
a) Read and write b) delete c) Appending d) None of these
3) What is the use of tell() function?
a) Return the file's current position b) Return the files previous position
c) Return the files end position d) None of these
4) What is the use of 'r' mode?
a) Write b) only Read c) Read and Write d) Above all
5) Which of the following function reads the text from file by line by line?
(a)file.read() (b)file.readLine() (c) file.readline() (d) file.readlines()
6) what is the function to read all lines from a file? When file = open(" read_it.txt", "r")
(a) file.read lines() (b)file.read() (c)read(file) (d) none
7) What is the new line tag in python?
(a) print "\n" (b) print "n" (c) "/n") (d) new line
8) What is the function to close a file? If file=open("object.txt","r")?
(a) file.close() (b)object.close() (c) close() (d) none
9) Which one of the following is the correct function to read a file? When f=open("file.txt","r") (a) f.read() (b)
f(read) (c)read.f() (d) none
10) When we use w mode in opening file, what does it mean?
(a) to append text (b) to read text (c) to create new file (d) none
Solved problems
1) Write a Python program to compare two files to check whether they are identical or not.
OUTPUT
3) Write a program to read the record of a particular student.
Programs to do
1) Write a Python program to count the frequency of words in a file.
2) Write a Python program to merge contents of two text files and store it in a new text file.
3) Write a Python program to read a text file and perform following operations.
a) Count of alphabets
b) Count of Vowels
c) Count of consonants
d) Count of digits
e) Count of special characters
4) Write a program to accept a filename from the user and display all the lines from the file which contain python
comment character '#'.
5) Write a Python program to replace a line in the given text file.