Python Lab Workbook - Final - 2021 - Updated
Python Lab Workbook - Final - 2021 - Updated
(Computer Science)
SECC - I
CS-3510 PYTHON PROGRAMMING
Semester V
(From Academic Year 2021)
College Division
Academic Year
This lab-book is intended to be used by T.Y.B.Sc(Computer Science) students for SECC - I CS-3510
Python Programming , Semester V.
• Difficulty Levels
Self Activity: Students should solve these exercises for practice only.
SET A - Easy: All exercises are compulsory.
SET B - Medium: All exercises are compulsory.
Programs for practice: all these programs are for homework.
Signature of Incharge:
T.Y.B.Sc(Comp.Sc.)Lab–II,Sem–I [Page5]
How to Install Jupyter Notebook on Ubuntu 20.04 / 18.04
How to install Jupyter Notebook on Ubuntu 20.04 to share live code with others. In this guide, we’ll show you how
to Install Jupyter Notebook on Ubuntu 20.04 LTS. Here we show you simple ways to install Jupyter on Ubuntu 20.04
LTS (Focal Fossa). You can follow the same instructions for Ubuntu 18.04, 16.04 and any other Debian based
distribution like Linux Mint and Elementary OS.
Jupyter Notebook is an open-source web application that allows you to create and share live code documents
with others. Jupyter is a next-generation notebook interface. Jupyter supports more than 40 programming languages
including Python, R, Julia, and Scala.
Note: Here, -H stands for security policy to set the home environment variable.
Step 4 Create Python Virtual Environment
First you have to create a directory in your home directory (or any other location). This new directory is
considered our code directory.
mkdir notebook
Next you have to go to the directory and create a Python virtual environment called jupyterenv.
6
cd notebook
virtualenv jupyterenv
Now we have to load and activate the virtual environment using the following command.
source jupyterenv/bin/activate
jupyter notebook
You have to click on the new menu and select Python3 or else you can select another option. It will create a
new page in your browser of Jupyter.
7
Step 7 Create Jupyter Application Menu
Create a new file called run-jupyter.sh in your notebook directory.
#!/bin/bash
source /home/username/jupyterenvironment/bin/activate
jupyter notebook
Create a new file in /usr/share/applications called jupyter.desktop to create an application menu item.
[Desktop Entry]
Name=Jupyter Notebook
Exec=/home/username/notebook/run-jupyter.sh
Type=Application
Terminal=true
8
What is Anaconda?
Anaconda is a free and open-source platform for programming languages such as Python and R. This platform comes
with the Python interpreter and various packages that are related to Artificial Intelligence.
The main agenda behind the Anaconda Platform is to make it easy for people who are keenly interested in these
fields. It comes with many pre-installed libraries and packages and it just needs a single installation process.
This platform is beginner-friendly and easy to use.
• Install Python and Jupyter using the Anaconda Distribution: Includes Python, the Jupyter Notebook,
and other commonly used packages for scientific computing and data science.
• Using PIP command:
Install Jupyter using the PIP package manager used to install and manage software packages/libraries
written in Python.
Installing Jupyter Notebook using Anaconda
Anaconda platform also contains Jupyter, Spyder, and more. This is mainly used for large data processing, data
analytics, heavy scientific computing. One sub-application of anaconda is Spyder that is used for Python. OpenCV
Library for image processing which is used in Python also works in Spyder. Package versions are managed by the
package management system called Conda.
In order to install Jupyter using Anaconda, Please follow the following instructions:
1. Install Anaconda:
9
2. Please go to the Anaconda.com/downloads site
10
4. Download the .exe installer
11
6. Launch Anaconda Navigator
12
8. Beginning the Installation
9. Loading Packages
13
Installing Jupyter Notebook using pip command
PIP stands for the package management system which is used to install and manage software packages/libraries.
These libraries and the packages are written in Python. These files are stored in a large “on-line repository” termed
as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. Before we
start installing pip, we have to check the version of the pip command. If the version of the pip command is not
updated then we need to update the pip in our system.
Update PIP command
python3 -m pip install --upgrade pip
Then after updating the pip version we need to follow the upcoming process to install Jupyter.
• Command to install Jupyter: pip3 install Jupyter
• Begin Installation
• Collect Files and Data
• Download Packages
• Run Installation
• Finish Installation
Now Launch the Jupyter:
Use the command to launch Jupyter using command-line:
jupyter notebook
15
# 1. Know the basic syntax, data types, control structures and conditional statements.
# 2. Learn error handling and file I/O.
# 3. Read about exception handling and regular expression.
# 4. Write functions and use of list, tuple, set and dictionary concepts.
def main():
print("Let's start to learn Python.")
...
Docstring in Python
Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick
notes with every Python module, function, class, and method. You can define a docstring by adding it as a string
constant. It must be the first statement in the object’s (module, function, class, and method) definition. The docstring
has a much wider scope than a Python comment. Hence, it should describe what the function does, not how. Also, it
is a good practice for all functions of a program to have a docstring.
How to define docstring in Python?
You can define a docstring with the help of triple-quotation mark. Add one in the beginning and second at the end
of the string. Just like multiline comments, docstring can also overlap to multiple lines.
Note: The strings defined using triple-quotation mark are docstring in Python. However, it might appear to you as
a regular comment.
What is the difference between a comment and the docstring?
The strings beginning with triple quotes are still regular strings except the fact that they could spread to multiple
lines. It means they are executable statements. And if they are not labeled, then they will be garbage collected as
soon as the code executes.
The Python interpreter won’t ignore them as it does with the comments. However, if such a string is placed
immediately after a function or class definition or on top of a module, then they turn into docstrings. You can access
them using the following special variable. myobj.__doc__
def theFunction():
'''
This function demonstrate the use of docstring in Python.
'''
print("Python docstrings are not comments.")
print("\nJust printing the docstring value...")
print(theFunction. doc )
16
Summary Python comment and docstring
Comments and docstrings add values to a program. They make your programs more readable and maintainable.
Even if you need to refactor the same code later, then it would be easier to do with comments available.
Software spends only 10% time of its life in development and rest of 90% in maintenance.
Hence, always put relevant and useful comments or docstrings as they lead to more collaboration and speed up the
code refactoring activities.
Operators in Python
Arithmetic operators
With arithmetic operators, we can do various arithmetic operations like addition, subtraction, multiplication, division,
modulus, exponent, etc. Python provides multiple ways for arithmetic calculations like eval function, declare variable
& calculate, or call functions.
Operator Purpose Usage
+ Addition – Sum of two operands a+b
– Subtraction – Difference between the two operands a-b
* Multiplication – Product of the two operands a*b
/ Float Division – Quotient of the two operands a/b
// Floor Division – Quotient of the two operands (Without fractional part) a//b
% Modulus – Integer remainder after division of ‘a’ by ‘b.’ a%b
** Exponent – Product of ‘a’ by itself ‘b’ times (a to the power of b) a**b
a=5
b=3
print('Sum : ', a+b)
print('Subtraction : ', a-b)
print('Multiplication : ', a*b)
print('Division (float) : ', a/b)
print('Division (floor) : ', a//b)
print('Modulus : ', a%b)
print('Exponent : ', a**b)
Output-
Sum : 8
Subtraction : 2
Multiplication : 15
Division (float) : 1.66666666667
Division (floor) : 1
17
Modulus : 2
Exponent : 125
Comparison operators
In Python programming, comparison operators allow us to determine whether two values are equal or if one is
higher than the other and then make a decision based on the result.
Operator Purpose Usage
> Greater than – if the left operand is greater than the right, then it returns true. a>b
< Less than – if the left operand is less than the right, then it returns true. a<b
== Equal to – if two operands are equal, then it returns true. a==b
!= Not equal to – if two operands are not equal, then it returns true. a!=b
>= Greater than or equal – if the left operand is greater than or equal to the right,
then it returns true. a>=b
<= Less than or equal – if the left operand is less than or equal to the right, then
it returns true. a<=b
a=9
b=5
print('a > b is',a>b)
print('a < b is',a<b)
print('a == b is',a==b)
print('a != b is',a!=b)
print('a >= b is',a>=b)
print('a <= b is',a<=b)
Output-
a > b is True
a < b is False
a == b is False
a != b is True
a >= b is True
a <= b is False
18
Logical operators
Logical Python operators enable us to make decisions based on multiple conditions. The operands act as conditions
that can result in a true or false value. The outcome of such an operation is either true or false (i.e., a Boolean value).
However, not all of these operators return a boolean result. The ‘and’ and ‘or’ operators do return one of their
operands instead of pure boolean value. Whereas the ‘not’ operator always gives a real boolean outcome.
Operator Purpose Usage
and if ‘a’ is false, then ‘a’, else ‘b’ a and b
or if ‘a’ is false, then ‘b’, else ‘a’ a or b
not if ‘a’ is false, then True, else False not a
a=7
b=4
# Result: a and b is 4
print('a and b is',a and b)
# Result: a or b is 7
print('a or b is',a or b)
# Result: not a is False
print('not a is',not a)
Output-
a and b is 4
a or b is 7
not a is False
Bitwise operators
Bitwise Python operators process the individual bits of integer values. They treat them as sequences of binary bits.
We can use bitwise operators to check whether a particular bit is set. For example, IoT applications read data from
the sensors based on a specific bit is set or not. In such a situation, these operators can help.
Operator Purpose Usage
& Bitwise AND – compares two operands on a bit level and returns 1
if both the corresponding bits are 1 a&b
| Bitwise OR – compares two operands on a bit level and returns 1
if any of the corresponding bits is 1 a|b
~ Bitwise NOT – inverts all of the bits in a single operand ~a
^ Bitwise XOR – compares two operands on a bit level and returns 1
if any of the corresponding bits is 1, but not both a^b
>> Right shift – shifts the bits of ‘a’ to the right by ‘b’ no. of times a >> b
<< Left shift – shifts the bits of ‘a’ to the left by ‘b’ no. of times a << b
19
Let’s consider the numbers 4 and 6 whose binary representations are ‘00000100’ and ‘00000110’. Now, we’ll
perform the AND operation on these numbers.
a=4
b=6
#Bitwise AND: The result of 'a & b' is 4
print('a & b is',a & b)
Output-
a & b is 4
The above result is the outcome of following AND (‘&’) operation.
00000100&
00000110
Assignment operators
In Python, we can use assignment operators to set values into variables.
The instruction a = 4 uses a primitive assignment operator that assigns the value 4 to the left operand.
Below is the list of available compound operators in Python. For example, the statement a += 4 adds to the variable
and then assigns the same. It will evaluate to a = a + 4.
Operator Example Similar to
= a=4 a=4
+= a+=4 a=a+4
-= a-=4 a=a-4
*= a*=4 a=a*4
/= a/=4 a=a/4
%= a%=4 a=a%4
**= a**=4 a=a**4
&= a&=4 a=a&4
|= a|=4 a=a|4
^= a^=4 a=a^4
>>= a>>=4 a=a>>4
<<= a<<=4 a=<<4
20
Advanced Python operators
Python also bundles a few operators for special purposes. These are known as advanced Python operators like the
identity operator or the membership operator.
Identity operators
These operators enable us to compare the memory locations of two Python objects/variables. They can let us find
if the objects share the same memory address. The variables holding equal values are not necessarily identical.
Alternatively, we can use these operators to determine whether a value is of a specific class or type.
Operator Purpose Usage
is True – if both the operands refer to the same object, else False a is b (True if id(a) and
id(b) are the same)
is not True – if the operands refer to different objects, else False a is not b (True if id(a) and
id(b) are different)
Membership operators
Membership operators enable us to test whether a value is a member of other Python objects such as strings, lists,
or tuples.
In C, a membership test requires iterating through a sequence and checking each value. But Python makes it very
easy to establish membership as compared to C.
Also, note that this operator can also test against a dictionary but only for the key, not the value.
21
Operator Purpose Usage
in True – if the value exists in the sequence 7 in [3, 7, 9]
not in True – if the value doesn’t found in the sequence 7 not in [3, 5, 9]
# Using Membership operator
str = 'Python operators'
dict = {6:'June',12:'Dec'}
print('P' in str)
print('Python' in str)
print('python' not in str)
print(6 in dict)
print('Dec' in dict)
Output-
True
True
True
True
False
Conditional Statements
There comes situations in real life when we need to make some decisions and based on these decisions, we decide
what should we do next. Similar situations arise in programming also where we need to make some decisions and
based on these decisions we will execute the next block of code. Decision-making
statements in programming languages decide the direction of the flow of program execution. Decision-making
statements available in python are:
if statement
if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block
of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise
not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the 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.
22
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:-
23
else:
# Executes this block if
# condition is false
Flow Chart:-
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean 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.
24
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
Flow chart:-
26
print ("i is not present")
Output-
i is 20
Short Hand if statement
Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The
statement can be put on the same line as the if statement.
Syntax:
if condition: statement
# 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
# Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)
Output-
True
Python programming language provides following types of loops to handle looping requirements. Python provides
three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their
syntax and condition checking time.
Looping Statements
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied.
And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax :
while expression:
statement(s)
27
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
# Python program to illustrate
# while loop
count = 0
while (count < 2):
count = count + 1
print("Hello Maharashtra")
Output-
Hello Maharashtra
Hello Maharashtra
Iterating by index of sequences: We can also use the index of elements in the sequence to iterate. The key idea
is to first calculate the length of the list and in iterate over the sequence within the range of this length.
See the below example:
# Python program to illustrate # Iterating by index
list = ["cmcs", "for", "cmcs"]
for index in range(len(list)):
print list[index]
Output-
cmcs
for
cmcs
Using else statement with for loops: We can also combine else statement with for loop like in while loop. But as
there is no condition in for loop based on which the execution will terminate so the else block will be executed
immediately after for block finishes execution.
Below example explains how to do this:
# Python program to illustrate # combining else with for
list = ["cmcs", "for", "cmcs"]
for index in range(len(list)):
print list[index]
else:
print "Inside Else Block"
Output-
29
cmcs
for
cmcs
Inside Else Block
Nested Loops: Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we 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.
# Python program to illustrate # nested for loops in Python
from future import print_function
for i in range(1, 4):
for j in range(i):
print(i, end=' ')
print()
Output-
1
22
333
Loop Control Statements: 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.
30
Continue Statement: It returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
for letter in 'cmcsforcmcs':
if letter == 'c' or letter == 's':
continue
print 'Current Letter :', letter
var = 10
Output-
Current Letter : m
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : m
Break Statement: It brings control out of the loop
for letter in 'cmcsforcmcs':
# break the loop as soon it sees 'm'
# or 's'
if letter == 'm' or letter == 's':
break
print 'Current Letter :', letter
Output-
Current Letter : m
Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control statement,
function and classes.
# An empty loop
for letter in 'cmcsforcmcs':
pass
print 'Last Letter :', letter
Output-
Last Letter : s
31
Lab Assignments
SET A
1. Python Program to Calculate the Area of a Triangle
2. Python Program to Swap Two Variables
3. Python Program to Generate a Random Number
SET B
1. Write a Python Program to Check if a Number is Positive, Negative or Zero
2. Write a Python Program to Check if a Number is Odd or Even
3. Write a Python Program to Check Prime Number
4. Write a Python Program to Check Armstrong Number
5. Write a Python Program to Find the Factorial of a Number
PROGRAMS FOR PRACTICE:
1. Python Program to Convert Kilometers to Miles
2. Python Program to Convert Celsius To Fahrenheit
3. Write a Python Program to Check Leap Year
4. Write a Python Program to Print all Prime Numbers in an Interval
5. Write a Python Program to Print the Fibonacci sequence
6. Write a Python Program to Find Armstrong Number in an Interval
7. Write a Python Program to Find the Sum of Natural Numbers
Assignment Evaluation
32
Assignment 2 : Strings and Functions
Objectives
• Understand the syntax of strings in Python, How to get data from the user, to concatenate strings, to
interpolate with str.format(), Understand style guide and escape characters
• Understand the concept of function, identify formal parameters and parameter values in a code sample,
predict the return value of a function given sample parameter values, define functions with appropriate
names for formal parameter
Reading
You should read the following topics before starting this exercise
Strings: declaration, manipulation, special operations, escape character, string formatting operator, Raw String,
Unicode strings, Built-in String methods..
Definitions and Uses, Function Calls, Type Conversion Functions, Math Functions, Composition, Adding New
Functions, Flow of Execution, Parameters and Arguments, Variables and Parameters, Stack Diagrams, Void
Functions, Anonymous functions Importing with from, Return Values, Boolean Functions, More Recursion
Ready Reference and Self Activity
Python Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.
var1 ='Hello World!'
var2 ="Python Programming"
Updating Strings
33
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its
previous value or to a completely different string altogether. For example −
var1 ='Hello World!'
print"Updated String :- ", var1[:6]+'Python'
Output-
Updated String :- Hello Python
Operator Description
* Repetition - Creates new strings, concatenating multiple copies of the same string
[:] Range Slice - Gives the characters from the given range
not in Membership - Returns true if a character does not exist in the given string
r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw
strings is exactly the same as for normal strings with the exception of the raw string
operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r)
or uppercase (R) and must be placed immediately preceding the first quote mark.
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
34
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes used
are:
Typecode Value
%c character
%o octal integer
Symbol Functionality
- left justification
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
m.n. m is the minimum total width and n is the number of digits to display
after the decimal point (if appl.)
36
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs,
TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
para_str ="""this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str
Output-
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Note : how every single special character has been converted to its printed form, right down to the last NEWLINE
at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an
explicit carriage return at the end of a line or its escape code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays
the way you wrote it −
>>>print'C:\\nowhere'
Output-
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
>>>print r'C:\\nowhere'
Output-
C:\\nowhere
37
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode.
This allows for a more varied set of characters, including special characters from most languages in the world. I'll
restrict my treatment of Unicode strings to the following −
print u'Hello, world!'
Output-
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Functions in Python
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide
better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own
functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters
inside these parentheses.
39
• The first statement of a function can be an optional statement - the documentation string of the function
or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were
defined.
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures
the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly
from the Python prompt. Following is the example to call printme() function −
#Here, we are maintaining reference of the passed object and appending values in the same object.
Output-
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten
inside the called function.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist =[1,2,3,4];# This would assig new reference in mylist
print"Values inside the function: ", mylist
return
# Now you can call changeme function
mylist =[10,20,30];
changeme( mylist );
print"Values outside the function: ", mylist
#The parameter mylist is local to the function changeme.
#Changing mylist within the function does not affect mylist.
#The function accomplishes nothing and finally this would produce the following
Output-
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
41
Function Arguments
You can call a function by using the following types of formal arguments −
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
Output-
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to the printme() function
in the following ways −
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that
argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
# Function definition is here
def printinfo( name, age =35):
"This prints a passed info into this function"
print"Name: ", name
print"Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki")
printinfo( name="miki")
Output-
Name: miki
Age 50
Name: miki
Age 35
43
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These
arguments are called variable-length arguments and are not named in the function definition, unlike required and
default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This
tuple remains empty if no additional arguments are specified during the function call. Following is a simple example
# Function definition is here
def printinfo( arg1,*vartuple ):
"This prints a variable passed arguments"
print"Output is: "
print arg1
forvarin vartuple:
printvar
return;
# Now you can call printinfo function
printinfo(10)
printinfo(70,60,50)
Output-
Output is:
10
Output is:
70
60
50
Lab Assignments
SET A
Strings
1) Write a python program to check whether the string is Symmetrical or Palindrome
2) Write a python program to Reverse words in a given String
3) Write a python program to remove i’th character from string in different ways
Functions
1) Write a Python function to find the Max of three numbers.
2) Write a Python function to sum all the numbers in a list.
3) Write a Python program to reverse a string.
SET B
Strings
1. Write a python program to print even length words in a string
2. Write a python program to accept the strings which contains all vowels
3. Write a python program to Count the Number of matching characters in a pair of string
Functions
1. Write a Python function that takes a list and returns a new list with unique elements of the first list.
2. Write a Python function that takes a number as a parameter and check the number is prime or not.
3. Write a Python function to check whether a number is perfect or not.
Assignment Evaluation
49
How for loop in Python works internally?
Before proceeding to this section, you should have a prior understanding of Python Iterators.
Firstly, lets see how a simple for loop looks like.
# A simple for loop example
fruits = ["apple", "orange", "kiwi"]
for fruit in fruits:
print(fruit)
Output-
apple
orange
kiwi
Here we can see the for loops iterates over a iterable object fruits which is a list. Lists, sets, dictionary these are
few iterable objects while an integer object is not an iterable object.
For loops can iterate over any iterable object (example: List, Set, Dictionary, Tuple or String).
Now with the help of above example lets dive deep and see what happens internally here.
1. Make the list (iterable) an iterable object with help of iter() function.
2. Run a infinite while loop and break only if the StopIteration is raised.
3. In the try block we fetch the next element of fruits with next() function.
4. After fetching the element we did the operation to be performed in with the element. (i.e print(fruit))
list1 =['Maharashtra','Gujrat',1998,1999];
list2 =[1,2,3,4,5,6,7];
print"list1[0]: ", list1[0]
print"list2[1:5]: ", list2[1:5]
Output-
list1[0]: Maharashtra
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment
operator, and you can add to elements in a list with the append() method. For example −
list =['Maharashtra','Gujrat',1998,1999];
print"Value available at index 2 : "
print list[2]
list[2]=2001;
print"New value available at index 2 : "
print list[2]
Output-
Value available at index 2 :
51
1998
New value available at index 2 :
2001
Note − append() method is discussed in subsequent section.
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting
or the remove() method if you do not know. For example −
list1 =['Maharashtra','Gujrat',1998,1999];
print list1
del list1[2];
print"After deleting value at index 2 : "
print list1
Output-
['Maharashtra', 'Gujrat', 1998, 1999]
After deleting value at index 2 :
['Maharashtra', 'Gujrat', 1999]
Note − remove() method is discussed in subsequent section.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except
that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
tup1 =('Maharashtra','Gujrat',1998,1999);
tup2 =(1,2,3,4,5,6,7);
print"tup1[0]: ", tup1[0];
print"tup2[1:5]: ", tup2[1:5];
Output-
tup1[0]: Maharashtra
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take
portions of existing tuples to create new tuples as the following example demonstrates −
tup1 =(12,34.56);
tup2 =('abc','xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output-
(12, 34.56, 'abc', 'xyz')
55
Python Expression Results Description
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists,
parentheses for tuples, etc., default to tuples, as indicated in these short examples −
print'abc',-4.24e93,18+6.6j,'xyz';
x, y =1,2;
print"Value of x , y : ", x,y;
Output-
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
Pyhton Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is
enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the
keys must be of an immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
Following is a simple example −
56
dict ={'Name':'Amitabh','Age':7,'Class':'First'}
print"dict['Name']: ", dict['Name']
print"dict['Age']: ", dict['Age']
Output-
dict['Name']: Amitabh
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −
dict ={'Name':'Amitabh','Age':7,'Class':'First'}
print"dict['Arjun']: ", dict['Arjun']
Output-
dict['Arjun']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Arjun']: ", dict['Arjun'];
KeyError: 'Arjun'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example −
dict ={'Name':'Amitabh','Age':7,'Class':'First'}
dict['Age']=8;# update existing entry
dict['School']="CMCS School";# Add new entry
print"dict['Age']: ", dict['Age']
print"dict['School']: ", dict['School']
Output-
dict['Age']: 8
dict['School']: CMCS School
57
del dict['Name'];# remove entry with key 'Name'
dict.clear();# remove all entries in dict
del dict ;# delete entire dictionary
print"dict['Age']: ", dict['Age']
print"dict['School']: ", dict['School']
#Note that an exception is raised because after del dict dictionary does not exist any more −
Output-
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.
58
Built-in Dictionary Functions & Methods
Python includes the following dictionary functions −
Function Use
cmp(dict1, dict2) Compares elements of both dict.
len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
str(dict) Produces a printable string representation of a dictionary
type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
Python Set
Python’s built-in set type has the following characteristics:
• Sets are unordered.
• Set elements are unique. Duplicate elements are not allowed.
• A set itself may be modified, but the elements contained in the set must be of an immutable type.
Let’s see what all that means, and how you can work with sets in Python.
A set can be created in two ways. First, you can define a set with the built-in set() function:
x=set(<iter>)
59
In this case, the argument <iter> is an iterable—again, for the moment, think list or tuple—that generates the list of
objects to be included in the set. This is analogous to the <iter> argument given to the .extend() list method:
>>>x=set(['zoo','cat','jaz','zoo','box'])
>>>x
{'box', 'zoo', 'cat', 'jaz'}
>>>x=set(('zoo','cat','jaz','zoo','box'))
>>>x
{'box', 'zoo', 'cat', 'jaz'}
Strings are also iterable, so a string can be passed to set() as well. You have already seen that list(s) generates a list
of the characters in the string s. Similarly, set(s) generates a set of the characters in s:
>>>s='quux'
>>>list(s)
['q', 'u', 'u', 'x']
>>>set(s)
{'x', 'u', 'q'}
You can see that the resulting sets are unordered: the original order, as specified in the definition, is not necessarily
preserved. Additionally, duplicate values are only represented in the set once, as with the string 'zoo' in the first
two examples and the letter 'u' in the third.
Alternately, a set can be defined with curly braces ({}):
x={<obj>,<obj>,...,<obj>}
When a set is defined this way, each <obj> becomes a distinct element of the set, even if it is an iterable. This
behavior is similar to that of the .append() list method.
Thus, the sets shown above can also be defined like this:
>>>x={'zoo','cat','jaz','zoo','box'}
>>>x
{'box', 'zoo', 'cat', 'jaz'}
>>>x={'b','o','o','x'}
>>>x
{'x', 'b', 'o'}
To recap:
• The argument to set() is an iterable. It generates a list of elements to be placed into the set.
• The objects in curly braces are placed into the set intact, even if they are iterable.
Observe the difference between these two set definitions:
60
>>>{'zoo'}
{'zoo'}
>>>set('zoo')
{'o', 'z'}
A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty dictionary, so the
only way to define an empty set is with the set() function:
>>>x=set()
>>>type(x)
<class 'set'>
>>>x
set()
>>>x={}
>>>type(x)
<class 'dict'>
An empty set is falsy in a Boolean context:
>>>x=set()
>>>bool(x)
False
>>>xor1
1
>>>xand1
set()
You might think the most intuitive sets would contain similar objects—for example, even numbers or surnames:
>>>s1={2,4,6,8,10}
>>>s2={'Smith','McArthur','Wilson','Johansson'}
Python does not require this, though. The elements in a set can be objects of different types:
>>>x={42,'zoo',3.14159,None}
>>>x
{None, 'zoo', 42, 3.14159}
Don’t forget that set elements must be immutable. For example, a tuple may be included in a set:
>>>x={42,'zoo',(1,2,3),3.14159}
>>>x
{42, 'zoo', 3.14159, (1, 2, 3)}
61
But lists and dictionaries are mutable, so they can’t be set elements:
>>>a=[1,2,3]
>>>{a}
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
{a}
TypeError: unhashable type: 'list'
>>>d={'a':1,'b':2}
>>>{d}
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
{d}
TypeError: unhashable type: 'dict'
Operating on a Set
Many of the operations that can be used for Python’s other composite data types don’t make sense for sets. For
example, sets can’t be indexed or sliced. However, Python provides a whole host of operations on set objects that
generally mimic the operations that are defined for mathematical sets.
Operators vs. Methods
Most, though not quite all, set operations in Python can be performed in two different ways: by operator or by method.
Let’s take a look at how these operators and methods work, using set union as an example.
Given two sets, x1 and x2, the union of x1 and x2 is a set consisting of all elements in either set.
62
Consider these two sets:
x1={'zoo','cat','jaz'}
x2={'jaz','box','quux'}
The union of x1 and x2 is {'zoo', 'cat', 'jaz', 'box', 'quux'}.
Note: Notice that the element 'jaz', which appears in both x1 and x2, appears only once in the union. Sets never
contain duplicate values.
63
Compute the union of two or more sets.
x1.union(x2[, x3 ...])
x1 | x2 [| x3 ...]
Set Union
x1.union(x2) and x1 | x2 both return the set of all elements in either x1 or x2:
>>>
>>>x1={'zoo','cat','jaz'}
>>>x2={'jaz','box','quux'}
>>>x1.union(x2)
{'zoo', 'box', 'quux', 'jaz', 'cat'}
>>>x1|x2
{'zoo', 'box', 'quux', 'jaz', 'cat'}
More than two sets may be specified with either the operator or the method:
>>>a={1,2,3,4}
>>>b={2,3,4,5}
>>>c={3,4,5,6}
>>>d={4,5,6,7}
>>>a.union(b,c,d)
{1, 2, 3, 4, 5, 6, 7}
>>>a|b|c|d
64
{1, 2, 3, 4, 5, 6, 7}
The resulting set contains all elements that are present in any of the specified sets.
Compute the intersection of two or more sets.
x1.intersection(x2[, x3 ...])
x1 & x2 [& x3 ...]
Set Intersection
x1.intersection(x2) and x1 & x2 return the set of elements common to both x1 and x2:
>>>x1={'zoo','cat','jaz'}
>>>x2={'jaz','box','quux'}
>>>x1.intersection(x2)
{'jaz'}
>>>x1&x2
{'jaz'}
You can specify multiple sets with the intersection method and operator, just like you can with set union:
>>>a={1,2,3,4}
>>>b={2,3,4,5}
>>>c={3,4,5,6}
>>>d={4,5,6,7}
>>>a.intersection(b,c,d)
{4}
>>>a&b&c&d
{4}
The resulting set contains only elements that are present in all of the specified sets.
Compute the difference between two or more sets.
x1.difference(x2[, x3 ...])
x1 - x2 [- x3 ...]
65
Set Difference
x1.difference(x2) and x1 - x2 return the set of all elements that are in x1 but not in x2:
>>>
>>>x1={'zoo','cat','jaz'}
>>>x2={'jaz','box','quux'}
>>>x1.difference(x2)
{'zoo', 'cat'}
>>>x1-x2
{'zoo', 'cat'}
Another way to think of this is that x1.difference(x2) and x1 - x2 return the set that results when any elements
in x2 are removed or subtracted from x1.
Once again, you can specify more than two sets:
>>>a={1,2,3,30,300}
>>>b={10,20,30,40}
>>>c={100,200,300,400}
>>>a.difference(b,c)
{1, 2, 3}
>>>a-b-c
{1, 2, 3}
When multiple sets are specified, the operation is performed from left to right. In the example above, a - b is
computed first, resulting in {1, 2, 3, 300}. Then c is subtracted from that set, leaving {1, 2, 3}:
66
Compute the symmetric difference between sets.
x1.symmetric_difference(x2)
x1 ^ x2 [^ x3 ...]
67
As with the difference operator, when multiple sets are specified, the operation is performed from left to right.
Curiously, although the ^ operator allows multiple sets, the .symmetric_difference() method doesn’t:
>>>
>>>a={1,2,3,4,5}
>>>b={10,2,3,4,50}
>>>c={1,50,100}
>>>a.symmetric_difference(b,c)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.symmetric_difference(b,c)
TypeError: symmetric_difference() takes exactly one argument (2 given)
x1.isdisjoint(x2)
Determines whether or not two sets have any elements in common.
x1.isdisjoint(x2) returns True if x1 and x2 have no elements in common:
>>>x1={'zoo','cat','jaz'}
>>>x2={'jaz','box','quux'}
>>>x1.isdisjoint(x2)
False
>>>x2-{'jaz'}
{'quux', 'box'}
>>>x1.isdisjoint(x2-{'jaz'})
True
If x1.isdisjoint(x2) is True, then x1 & x2 is the empty set:
>>>x1={1,3,5}
>>>x2={2,4,6}
>>>x1.isdisjoint(x2)
True
>>>x1&x2
set()
Note: There is no operator that corresponds to the .isdisjoint() method.
Modifying a Set
Although the elements contained in a set must be of immutable type, sets themselves can be modified. Like the
operations above, there are a mix of operators and methods that can be used to change the contents of a set.
Augmented Assignment Operators and Methods
Each of the union, intersection, difference, and symmetric difference operators listed above has an augmented
assignment form that can be used to modify a set. For each, there is a corresponding method as well.
72
>>>x={'zoo','cat','jaz'}
>>>x.remove('jaz')
>>>x
{'cat', 'zoo'}
>>>x.remove('box')
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
x.remove('box')
KeyError: 'box'
>>>x={'zoo','cat','jaz'}
>>>x.discard('jaz')
>>>x
{'cat', 'zoo'}
>>>x.discard('box')
>>>x
{'cat', 'zoo'}
73
>>>x
set()
>>>x.pop()
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
x.pop()
KeyError: 'pop from an empty set'
>>>x={'zoo','cat','jaz'}
>>>x
{'zoo', 'cat', 'jaz'}
>>>x.clear()
>>>x
set()
Frozen Sets
Python provides another built-in type called a frozenset, which is in all respects exactly like a set, except that a
frozenset is immutable. You can perform non-modifying operations on a frozenset:
>>>x=frozenset(['zoo','cat','jaz'])
>>>x
frozenset({'zoo', 'jaz', 'cat'})
>>>len(x)
3
>>>x&{'jaz','box','quux'}
frozenset({'jaz'})
74
AttributeError: 'frozenset' object has no attribute 'add'
>>>x.pop()
Traceback (most recent call last):
File "<pyshell#129>", line 1, in <module>
x.pop()
AttributeError: 'frozenset' object has no attribute 'pop'
>>>x.clear()
Traceback (most recent call last):
File "<pyshell#131>", line 1, in <module>
x.clear()
AttributeError: 'frozenset' object has no attribute 'clear'
>>>x
frozenset({'zoo', 'cat', 'jaz'})
Deep Dive: Frozensets and Augmented Assignment
Since a frozenset is immutable, you might think it can’t be the target of an augmented assignment operator. But
observe:
>>>f=frozenset(['zoo','cat','jaz'])
>>>s={'jaz','box','quux'}
>>>f&=s
>>>f
frozenset({'jaz'})
What gives?
Python does not perform augmented assignments on frozensets in place. The statement x &= s is effectively
equivalent to x = x & s. It isn’t modifying the original x. It is reassigning x to a new object, and the
object x originally referenced is gone.
You can verify this with the id() function:
>>>f=frozenset(['zoo','cat','jaz'])
>>>id(f)
56992872
>>>s={'jaz','box','quux'}
75
>>>f&=s
>>>f
frozenset({'jaz'})
>>>id(f)
56992152
f has a different integer identifier following the augmented assignment. It has been reassigned, not modified in
place.
Some objects in Python are modified in place when they are the target of an augmented assignment operator. But
frozensets aren’t.
Frozensets are useful in situations where you want to use a set, but you need an immutable object. For example,
you can’t define a set whose elements are also sets, because set elements must be immutable:
>>>x1=set(['zoo'])
>>>x2=set(['cat'])
>>>x3=set(['jaz'])
>>>x={x1,x2,x3}
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
x={x1,x2,x3}
TypeError: unhashable type: 'set'
If you really feel compelled to define a set of sets (hey, it could happen), you can do it if the elements are
frozensets, because they are immutable:
>>>x1=frozenset(['zoo'])
>>>x2=frozenset(['cat'])
>>>x3=frozenset(['jaz'])
>>>x={x1,x2,x3}
>>>x
{frozenset({'cat'}), frozenset({'jaz'}), frozenset({'zoo'})}
Likewise, recall from the previous tutorial on dictionaries that a dictionary key must be immutable. You can’t use
the built-in set type as a dictionary key:
>>>x={1,2,3}
>>>y={'a','b','c'}
>>>
>>>d={x:'zoo',y:'cat'}
76
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
d={x:'zoo',y:'cat'}
TypeError: unhashable type: 'set'
If you find yourself needing to use sets as dictionary keys, you can use frozensets:
>>>x=frozenset({1,2,3})
>>>y=frozenset({'a','b','c'})
>>>
>>>d={x:'zoo',y:'cat'}
>>>d
{frozenset({1, 2, 3}): 'zoo', frozenset({'c', 'a', 'b'}): 'cat'}
Lab Assignments
SET A
List
1) Write a Python program to sum all the items in a list.
2) Write a Python program to multiplies all the items in a list.
3) Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a
given list of non-empty tuples.
Tuples
1) Write a Python program to create a tuple.
2) Write a Python program to create a tuple with different data types.
3) Write a Python program to check whether an element exists within a tuple.
Sets
1) Write a Python program to create a set.
2) Write a Python program to iterate over sets.
3) Write a Python program to create set difference.
Dictionary
1) Write a Python script to sort (ascending and descending) a dictionary by value.
2) Write a Python script to add a key to a dictionary.
3) Write a Python program to iterate over dictionaries using for loops.
SET B
List
1. Write a Python program to remove duplicates from a list.
2. Write a Python program to check a list is empty or not.
77
Tuples
1. Write a Python program to convert a list to a tuple.
2. Write a Python program to remove an item from a tuple.
3. Write a Python program to slice a tuple.
4. Write a Python program to find the length of a tuple.
Sets
1. Write a Python program to check if a set is a subset of another set.
2. Write a Python program to find maximum and the minimum value in a set.
3. Write a Python program to find the length of a set.
Dictionary
1. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form
(x, x*x).
2. Write a Python script to merge two Python dictionaries.
3. Write a Python program to get a dictionary from an object's fields.
78
19. Write a Python program to reverse a tuple.
20. Write a Python program to convert a list of tuples into a dictionary.
21. Write a Python program to print a tuple with string formatting.
22. Write a Python program to create a symmetric difference.
23. Write a Python program to check if a given value is present in a set or not.
24. Write a Python program to check if a given set is superset of itself and superset of another given set.
25. Write a Python program to check a given set has no elements in common with other given set.
26. Write a Python program to remove the intersection of a 2nd set from the 1st set.
27. Write a Python program to remove duplicates from Dictionary.
28. Write a Python script to check whether a given key already exists in a dictionary.
29. Write a Python program to sum all the items in a dictionary.
30. Write a Python program to multiply all the items in a dictionary.
31. Write a Python program to remove a key from a dictionary.
Assignment Evaluation
79
Reading
You should read the following topics before starting this exercise
Concept file operations, Types of file modes (text or binary), File access modes for read, write and append file.
Types Of file in Python, Binary files in Python,Text files in Python,Python file handling operations,Python Create
and Open a File.
Concept of date and Time in python
Ready Reference and Self Activity
The file handling plays an important role when the data needs to be stored permanently into the file. A file is
a named location on disk to store related information. We can access the stored information (non-volatile)
after the program termination. The file-handling implementation is slightly lengthy or complicated in the other
programming language, but it is easier and shorter in Python.
Types of File in Python
There are two types of files in Python and each of them is explained below in detail with examples for your
easy understanding.
They are:
1. Binary file
2. Text file
Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal text editor but we can’t read
the content present inside the file. That’s because all the binary files will be encoded in the binary format, which can
be understood only by a computer or machine.
For handling such binary files, we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise, you need a .pdf reader software
to open .pdf binary files and you need a photo editor software to read the image files and so on.
Text files in Python
Text files don’t have any specific encoding and it can be opened in normal text editor itself.
80
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
81
print (file.read(5))
82
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
my_file.close()
83
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
#Compile this program and pass two command line arguments: filename and string to search.
Python datetime
Python has a module named datetime to work with dates and times. Let's create a few simple programs related to
date and time before we dig deeper.
#Get Current Date and Time
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
Output-
2021-12-19 09:26:03.478039
Here, we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime
object containing the current local date and time.
#Get Current Date
import datetime
date_object = datetime.date.today()
print(date_object)
Output-
2021-12-19
In this program, we have used today() method defined in the date class to get a date object containing the current
local date.
Inside datetime
We can use dir() function to get a list containing all attributes of a module.
#use of dir()
import datetime
print(dir(datetime))
Output-
84
['MAXYEAR', 'MINYEAR', ' builtins ', ' cached__', ' doc ', ' file ', ' loader ', '__name ',
' package ', ' spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone',
'tzinfo']
If you are wondering, date() in the above example is a constructor of the date class. The constructor takes three
arguments: year, month and day.
The variable d1 is a date object.
We can only import date class from the datetime module. Here's how:
# Date object to represent a date
from datetime import date
d1 = date(2021, 4, 13)
print(d1)
You can create a date object containing the current date by using a classmethod named today().
# Get current date
from datetime import date
today = date.today()
print("Current date =", today)
85
Python format datetime
The way date and time is represented may be different in different places, organizations etc. It's more common to
use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.
Python has strftime() and strptime() methods to handle this.
Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more format codes and returns a
formatted string based on it.
In the above program, t, s1 and s2 are strings.
%Y - year [0001,..., 2020, 2021,..., 9999]
%m - month [01, 02, ..., 11, 12]
%d - day [01, 02, ..., 30, 31]
%H - hour [00, 01, ..., 22, 23
86
%M - minute [00, 01, ..., 58, 59]
%S - second [00, 01, ..., 58, 59]
87
Local time: 2018-12-20 13:10:44.260462
America/New_York time: 2018-12-20 13:10:44.260462
Europe/London time: 2018-12-20 13:10:44.260462
Here, datetime_NY and datetime_London are datetime objects containing the current date and time of their
respective timezone.
Lab Assignments
SET A
1. Write a Python program to read an entire text file.
2. Write a Python program to compute the number of characters, words and lines in a file.
3. Write a Python script to print the current date in following format “Sun May 29 02:26:23
IST 2017”
SET B
1. Write a Python program to append text to a file and display the text.
2. Write a Python program to print each line of a file in reverse order.
3. Write a Python program to print date, time for today and now.
PROGRAMS FOR PRACTICE:
1. Write a Python program to read an entire text file.
2. Write a Python program to read first n lines of a file.
3. Write a Python program to append text to a file and display the text.
4. Write a Python program to read last n lines of a file.
5. Write a Python program to read a file line by line and store it into a list.
6. Write a Python program to read a file line by line store it into a variable.
7. Write a Python program to read a file line by line store it into an array.
8. Write a python program to find the longest words.
9. Write a Python program to count the number of lines in a text file.
10. Write a Python program to count the frequency of words in a file.
11. Write a Python program to get the file size of a plain file.
12. Write a Python program to write a list to a file.
13. Write a Python program to copy the contents of a file to another file .
14. Write a Python program to combine each line from first file with the corresponding line in second file.
15. Write a Python program to remove newline characters from a file.
88
16. Write a Python program that takes a text file as input and returns the number of words of a given text file.
Note: Some words can be separated by a comma with no space.
17. Write a Python program to extract characters from various text files and puts them into a list.
18. Write a python program to get Current Time
19. Get Current Date and Time using Python
20. Write a python | Find yesterday’s, today’s and tomorrow’s date
21. Write a python program to convert time from 12 hour to 24 hour format
22. Write a python program to find difference between current time and given time
23. Write a python Program to Create a Lap Timer
24. Convert date string to timestamp in Python
25. Find number of times every day occurs in a Year
Assignment Evaluation
89
Reading
You should read the following topics before starting this exercise
Concept of Exception, Handling Exceptions - Use of try....except...else keywords, Exception with Arguments,
User-defined Exceptions.
Concept of regular expression, various types of regular expressions, using match function.
Ready Reference and Self Activity
Exception:
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of
the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
Handling an Exception
If you have some suspicious code that may raise an exception, you can defend your program by placing the
suspicious code in a try: block. 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:
You do your operations 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
This example tries to open a file where you do not have write permission, so it raises an exception.
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"
This produces the following result −
Error: can't find file or read data
The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as follows −
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
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except
91
statement is not considered a good programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that may occur.
The except Clause with Multiple Exceptions.
You can also use the same except statement to handle multiple exceptions as follows-
try:
You do your operations here;
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
else:
If there is no exception then execute this block.
If you do not have permission to open the file in writing mode, then this will produce the following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
try:
fh = open("testfile", "w")
try:
92
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to the finally block. After
all the statements in the finally block are executed, the exception is raised again and is handled in the except
statements if present in the next higher layer of the try-except statement.
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.
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are
classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be
done as follows –
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class
object or simple string. For example, to capture above exception, we must write the except clause as follows
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
93
else:
Rest of the code here...
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
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
94
groups() function of match object to get matched expression.
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
Output-
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
The search Function
This function searches for first occurrence of RE pattern within string with optional flags.
Here is the syntax for this function −
re.search(pattern, string, flags=0)
Here is the description of the parameters −
Parameter Description
Pattern This is the regular expression to be matched.
String This is the string, which would be searched to match the pattern anywhere in the string.
Flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the
table below.
The re.search function returns a match object on success, none on failure. We use group(num) or groups()
function of match object to get matched expression.
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
95
else:
print "Nothing found!!"
Lab Assignments
SET A
1. Write a Python program to demonstrate the zero division error and overflow error.
2. Write a Python program to find sequences of lowercase letters joined with a underscore
3. Write a python program to Check if String Contain Only Defined Characters using Regex
SET B
1. Write a Python program to match a string that contains only upper and lowercase letters,
numbers, and underscores.Write a Python program to raised the attribute error, if attribute
class object has no attribute with the name attribute.
2. Write a python Program to Remove duplicate words from Sentence
3. Write a python to| Remove all characters except letters and numbers
96
13. Write a python Program to Check if email address valid or not
14. Write a python program to find files having a particular extension using RegEx
15. Write a python program to extract IP address from file
16. Write a python program to check the validity of a Password
Students can practice Common Examples of Exception as:
1. Division by Zero
2. Accessing a file which does not exist.
3. Addition of two incompatible types
4. Trying to access a nonexistent index of a sequence
5. Removing the table from the disconnected database server.
6. ATM withdrawal of more than the available amount
Assignment Evaluation
97