Complete Python WITH HEADER Final - Review

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 190

PYTHON 1

Contents
1.INTRODUCTION ..................................................................................................................................... 6
History of python ...................................................................................................................................... 6
Need of python programming ................................................................................................................... 7
Applications of Python programming ...................................................................................................... 9
Basics of python programming using REPL(shell) ................................................................................ 10
Variables ................................................................................................................................................. 15
Keywords .............................................................................................................................................. 18
Python Input- Output ............................................................................................................................. 26
Python Indentation .................................................................................................................................. 28
2.TYPES ,OPERATORS AND EXPRESSIONS ....................................................................................... 32
Types ....................................................................................................................................................... 32
Python numbers .................................................................................................................................. 32
Strings ................................................................................................................................................. 36
Boolean data types .............................................................................................................................. 40
Operators ................................................................................................................................................. 41
Arithmetic operators ........................................................................................................................... 41
Logical operators ................................................................................................................................ 43
Comparision operators ........................................................................................................................ 44
Assignment operators.......................................................................................................................... 45
Bitwise Operators................................................................................................................................ 47
Membership Operators........................................................................................................................ 48
Identity operators ................................................................................................................................ 49
Expressions ............................................................................................................................................. 50
Order of evaluations ................................................................................................................................ 50
Control flow ............................................................................................................................................ 51
if statement .......................................................................................................................................... 51
if- else statement ................................................................................................................................. 52
if-elif-else statement............................................................................................................................ 52
Nested if statement .............................................................................................................................. 53

VLITS II YEAR STUDENTS &STAFF


PYTHON 2

for loop ................................................................................................................................................ 54


while statement ................................................................................................................................... 55
break statement ................................................................................................................................... 57
continue statement .............................................................................................................................. 57
pass statement ..................................................................................................................................... 58
3.DATA STRUCTURES ............................................................................................................................ 63
Need for data structure ...................................................................................................................................... 63
Lists ......................................................................................................................................................... 64
List operations ..................................................................................................................................... 70
List methods ........................................................................................................................................ 71
Slicing in python ................................................................................................................................. 73
Tuples...................................................................................................................................................... 73
Sets .......................................................................................................................................................... 82
Dictionaries ............................................................................................................................................. 88
Sequences................................................................................................................................................ 94
Comprehensions...................................................................................................................................... 96
4.FUNCTIONS ......................................................................................................................................... 101
Introduction ........................................................................................................................................... 101
Defining functions ............................................................................................................................... 102
Calling functions ................................................................................................................................... 104
Passing arguments ................................................................................................................................. 105
Types of arguments ............................................................................................................................... 107
Required arguments .......................................................................................................................... 107
Keyword arguments .......................................................................................................................... 108
Default arguments ............................................................................................................................. 109
Variable-length arguments ................................................................................................................ 110
Anonymous functions ........................................................................................................................... 112
Fruitful functions .................................................................................................................................. 115
Recursive Functions .............................................................................................................................. 118
Scope of variables in functions ............................................................................................................. 120
Local and global variables ................................................................................................................ 120
Scope and Life time of variables........................................................................................................... 122

VLITS II YEAR STUDENTS &STAFF


PYTHON 3

Modules .................................................................................................................................................... 123


Creating modules .................................................................................................................................. 123
import statement.................................................................................................................................... 127
Name spacing ........................................................................................................................................ 129
Python Packages ....................................................................................................................................... 130
Introduction to PIP ................................................................................................................................ 130
Using python packages ......................................................................................................................... 132
5.OOP IN PYTHON ................................................................................................................................. 135
Overview of OOP Terminology............................................................................................................ 135
Classes .................................................................................................................................................. 136
Class methods and self -variables ......................................................................................................... 138
Constructor method............................................................................................................................... 142
Inheritance............................................................................................................................................. 144
Data hiding ............................................................................................................................................ 151
Error and Exceptions................................................................................................................................. 152
Difference between an error and exception .......................................................................................... 152
Handling exception ............................................................................................................................... 154
try except block ..................................................................................................................................... 154
Raising Exceptions................................................................................................................................ 157
Re-raising Exceptions ........................................................................................................................... 158
User Defined Exceptions ...................................................................................................................... 158
6. BRIEF TOUR OF THE STANDARD LIBRARY ............................................................................... 161
Operating system interface ................................................................................................................... 161
String pattern matching ......................................................................................................................... 163
Mathematics .......................................................................................................................................... 166
Internet access ....................................................................................................................................... 168
Dates and Times .................................................................................................................................... 170
Data Compression ................................................................................................................................. 173
Multithreading....................................................................................................................................... 174
GUI Programming ................................................................................................................................ 176
Turtle Graphics ..................................................................................................................................... 179
Testing ...................................................................................................................................................... 181

VLITS II YEAR STUDENTS &STAFF


PYTHON 4

Why testing is required? ....................................................................................................................... 182


Basic concepts of testing ....................................................................................................................... 182
Unit testing in python........................................................................................................................... 186
Writing Test cases ................................................................................................................................. 187
Running tests........................................................................................................................................ 189

VLITS II YEAR STUDENTS &STAFF


PYTHON 5

INTRODUCTION
 History of python
 Need of python programming
 Applications of python programming
 Basics of python programming using REPL(shell)
 Running python scripts
 Variables
 Keywords
 Input-output
 Indentation

VLITS II YEAR STUDENTS &STAFF


PYTHON 6

1.INTRODUCTION

Python is a powerful High-level,Object-oriented programming language. It has simple


easy-to-use syntax, that allows programmers to express concepts in fewer lines of code than
might be used in languages such as C++ or Java. Python interpreters are available for
many operating systems, allowing Python code to run on a wide variety of systems.
Before getting started let‘s get familiarized with the language first.

History of python
 Python is a fairly old language created by ―GUIDO VAN ROSSUM”.
 The design began in the late 1980‘s and was first released in February 1991.

Why python was created?


In late 1980‘s,Guido Van Rossum was working on the Amoeba distributed operating
system group. He wanted to use an interpreted language like ABC that could access the Amoeba
system calls. So he decided to create a language that was extensible. Finally this led to a design
of new language which was named after python.
 We can say that the python programming language is the successor of ABC language.
 The name ‗python‘ is given that, as he was very much fascinated to the famous British
comedy show named ‗Monty Python‘s Flying Circus‘.

Different Versions of Python:

 Major release python [3.0] was designed to rectify fundamental design faults in older
versions.
 Python [3.x] has a lot of new features added when compared to python [2.x] version.

VLITS II YEAR STUDENTS &STAFF


PYTHON 7

Major and better comparative features of [3.x] version than [2.x] version
 Solves faults or defects that included in 2.x version.
 There are lot of new features compared to 2.x
 Backward compatibility in 2.x is broken.
 [3.x] version is the future of python.
 Python [3.x] version supports more services which cannot be supported by [2.x] version.

Need of python programming


 The need of python of using python programming language can be expressed or
explained in several ways. But the major needs of using it simply are as described as
follows:
Major needs to choose python as first language:
1. Simple elegant syntax:
Programming in python is very easier. It‘s easier to understand and write the python
code. It‘s because the syntax feels very natural.

The above programming code makes us feel better to understand it easily that this code is about
to add two numbers and prints it.

2. Not overly strict:


 You don‘t need to define the type of variable in python. And also it is not necessary to
add semicolon at the end of the statement.
 Python enforces us to follow good practises like proper Indentation.
 It is comparatively much better than other programming languages in syntactical mode.

3. Expressiveness of the language:


 Python allows you to write programmes having greater functionalities with fewer lines of
code.

4. Great Community and support:


 Python has large supporting community.
 There are numerous active forums online which can be handled if you are stuck.
 It is more expressive.

5.The main need of python is that it is used for Backend Web Development.

VLITS II YEAR STUDENTS &STAFF


PYTHON 8

6. It supports Object Oriented Programming concepts.


7. It is interpreted language similar to PERL language.
8. It is powerful and fast. It plays well with others and it runs everywhere.
9. It is scripting language having its own tools and libraries which are predefined.
10.Python is very better in pre -processing the data compared to that of R-language.

VLITS II YEAR STUDENTS &STAFF


PYTHON 9

Applications of Python programming


1.Basically python is a general purpose language i.e., it can be used to develop general real time
applications.
Ex : (a) Booking of online tickets for movies
(b) Preparation of railway reservation application forms etc…
2.Artifcial Intelligence or Machine Learning:
Ex: playing a chess game with a computer making us defeat while playing with it. If we
are acknowledged with the certain task of playing chess perfectly we can defeat it too. Thus to
get a clear knowledge about a certain task Machine leaning leads a prominent role.
3.Data Analysis can be done easily:
Data analysis is a process of inspecting, cleaning, transforming, and modelling data with
the goal of discovering useful information , suggesting conclusions, and support design making.
4. It is also used to develop tools i.e., software. Also useful in developing games, apps, etc…
5. It works on cross platform operating systems and can be used across to develop a wide range
of applications including those intended for image processing and text processing.
6.Globally Used Applications:
Bit Torrent, YouTube, Drop Box, Deluge, Cinema-4D and Bazaar are a few globally used
applications based on python.
7.Technical Applications:
 It is used for web and internal development.
 Python has been used to create a variety of web-frame works including turbo gears, bottle
flasks etc…

VLITS II YEAR STUDENTS &STAFF


PYTHON 10

 Google App engine is one of the popular web application.


 It provides advanced content management systems.
 It supports all the features of basic languages like HTML and XML.
HTML: used for designing web page
XML: used for data transfer between web pages.
 It supports for file transfer protocall and also other internet protocalls.
 It is used for email processing.
 It supports Socket interface.
8.Scientific and Numeric Applications:
 It is useful in scientific computing.
 Used for editing and recording.
 Used for parallel computing.
 Used for image processing and graphic design applications.
 It is also used for language development.
 It is widely used on the server side.
 It is rather widely used for scripting. This includes various testing ,building,
deployment, monitoring, frameworks, scientific apps, and just quick scripts.
Hence we can find many real time applications by using python scripting language.

Basics of python interpreter


We can betterly understand the functionality of python interpreter when compared to C.
When we write a c program the code is compiled through preprocessors and transulator and
with .c extension it checks the predefined statements like printf( ),scanf( ) (in case any
information needed to be given from user and on ./a.out we get the result.In python,the work is
done by interpreter instead of compiler.
A interpreter is also a program that transulates a high level language into a low level one
according to its rules, but it does it at the moment the program is run. Interpreter executes source
code directly (usually inside its own virtual machine).
 It takes less amount of time to analyse the source code but the overall execution time is
slower.
 No intermediate object code is generated, hence are memory efficient.
 Continues translating the program until the first error is met, in which case it stops.Hence
debugging is easy.Thus,execution in python is very fast.
Compiler transulates the entire program before it is run.Interpreter transulate a line at a time
while the program is being run.

Basics of python programming using REPL(shell)


What is a REPL shell?
 Reads what you type
 Evaluates it

VLITS II YEAR STUDENTS &STAFF


PYTHON 11

 Prints out the return value ,then


 Loops back and does it all over again.
The symbol of three greater signs i.e >>> represents REPL shell.It is a simple,interactive
computer programming environment that takes input (single expressions),evaluates them and
returns the result to the user .If you type some code at REPL shell like
>>>print (―hello‖) and press enter ,REPL shell evaluates what you typed and returns the result.
Python has basically 2 modes.Interactive mode and script mode(normal mode).The normal mode
is the mode where the scripted and finished.py files are run in python interpreter.

Interactive mode
Interactive mode is a command line shell which gives immediate feedback for each
statement.This mode is good way to play around and try variations on syntax.We can invoke
python interpreter using two ways:

In Command prompt
On windows bring up the command prompt and type ―python‖,that prints a welcome message
stating its version and a copyright notice like below fig.Let it be (fig1).

The >>> is python‘s way of telling that we are in a interactive mode.A sample interactive
session:

VLITS II YEAR STUDENTS &STAFF


PYTHON 12

So we don‘t need to use any datatype,headerfiles etc…we can type in a single instruction, and
have the python interpreter execute it immediately.Line after the result has a REPL shell with a
cursor waiting for users other commands.

In Python IDLE
1. Go to Start
2. Search python IDLE in search bar
3. Open it
Python IDLE window will open with a welcome statements like the following:

Now it is the interacive mode of python IDLE.we can start coding right at the REPL shell.Let
this be (fig2).

Script mode
Instead of running python in interactive mode,we run it in script mode.We use script
mode when we want to execute a code which has more than one command.The code to be run
(called a script) is entered into a file (called module).We then ask python to run a script.Script
mode also can be done in two ways.

In Command prompt
1. Start
2. Search command prompt or type cmd
3. Open cmd
4. In cmd type python (check whether python is installed or not) .If it is installed you will get a
welcome message and some information (refer fig.1).
5. Now get out of python environment through cmd by command exit ( ).
6. So that we again come to cmd environment,here type edit filename.py or notepad filename.py
It means we are opening a file or a module in editor /notepad of some filename with .py
extension representing and indicating to OS that the file are a python script file.

VLITS II YEAR STUDENTS &STAFF


PYTHON 13

7.An editor will open,thus we can write our script in editor .When an editor/notepad is opened,it
is like the following with certain options.
 The editor is opened with a blue screen.
 It has a tool bar.
 The tool bar consists several options like:file,edit,search,view,options etc.
 At the bottom it shows in which line we are working with displaying‖ Line:number

The following fig. is the editor:

The following is a notepad:

8.Save the script(ctrl+s) written in editor/notepad and exit (ctrl+f+x) or another way is (alt+f+x).
Now again we come to cmd environment.
9.Now we need to run the script.For that type the following command ,
> python filename.py
(it means invoking the python interpreter to interpret the script written in filename.py and print
the result)
10.We will get the result of the interpreted script in the interactive shell.

VLITS II YEAR STUDENTS &STAFF


PYTHON 14

In python IDLE:(integrated development environment)


1.Start
2.Search Python IDLE in search bar
3.Open it.
4.A python interactive window will be opened.(refer fig. 2)
5.Now go to file and open new file.
A new window will be opened like this:

6.Type the script and save it before you run it.


7.Go to file and select save as to save.
8.Now go to Run and select run module.

This will executes our script code by restarting into python IDLE shell .For example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 15

On selecting run module:

Thus result is printed at interactive shell.

Variables
 These are nothing but reserved memory locations to store values.This means when we
create a variable we reserve some space in memory.
 Based on data type of variable, interpreter allocates memory and decides what can be
stored in the reserved memory.
 By assigning different data types to variables, we can store integers, decimals or
characters in their memory locations.
 Variables are also called as identifiers.
 Inside memory data will be updated as follows:
When x is 10 the memory diagram is as follows:

When x is 20 the memory diagram changes as follows:

As the value is varying or updating inside the memory thus it is called a variable.

Declaration
 Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign
(=) is used to assign values to variables.
 The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
 Python supports multiple assignment.
 It allows to assign a single value to several variables simultaneously that is a=b=c=1,here
3 variables are assigned to same memory locations.
 We can also assign multiple values to multiple variables in a single statement that is
a,b,c=1,2.5,‘python‘.

Rules for declaring variables


 Variables names must start with a letter or an underscore, such as:_python,python_

VLITS II YEAR STUDENTS &STAFF


PYTHON 16

 The remainder of your variable name may consist of letters, numbers and
underscores. Ex: n00b,password1…
 Names are case sensitive. Ex: case_sensitive, CASE_SENSITIVE, and
Case_Sensitive are each a different variable.
 Variable name should not starts with a letter or any special symbols.It shows an error
if it start with a number.
 We cannot use keywords as our variable names.

The conventions
 Readability is very important. Which of the following is easiest to read? I‘m hoping
you‘ll say the first example.
 python_puppet
 pythonpuppet
 pythonPuppet
 Descriptive names are very useful. If you are writing a program that adds up all of the
bad puns made in this book, which do you think is the better variable name?
 total_bad_puns
 super_bad
 Avoid using the lowercase letter ‗l‘, uppercase ‗O‘, and uppercase ‗I‘. Why? Because the
l and the I look a lot like each other and the number 1. And O looks a lot like 0.
Re-declaring variables
We can re-declare the variable even after you have declared it once.
Example:

Concatenating variables
 We can concatenate variables in python.
 We can concatenate different data type values like strings and integers.
 Unlike Java, which concatenates number with string without declaring number as string,
Python requires declaring the number as string otherwise it will show a type error.

VLITS II YEAR STUDENTS &STAFF


PYTHON 17

Example: In the below example, str (b) converts the integer data type to string data type .

Local and global variables


 When we want to use the same variable for rest of our program or module we declare it
as global variable.
 When we want to use the variable in a specific function or method we declare it as local
variable.We can use same variable as local and global variable.
 Python interpreter gives importance to local value and prints the updated value.
Let‘s see an example:

In the above example, f is declared as global and local variable at different scopes.

Using the keyword global, we can refer the global variable inside the function.

Deleting variables
We can also delete variables by using the command del ―variable name‖.
 If we delete variable and when we proceed to print, then we get an error.
 The error is ―variable name is not defined‖ which means we have already deleted the
variable.
 If a variable is deleted then memory allocated for that variable is also deleted.
 Accesing deleted memory is called as ―danzling memory‖.

VLITS II YEAR STUDENTS &STAFF


PYTHON 18

Example:

Multiple Assignment
Python allows programmer to assign single value for multiple variables simultaneously.

Keywords
Keywords are the reserved words in Python. We cannot use a keyword as variable
name,function name or any other identifier.

Keywords in python programming language

 The above may get altered in different versions of Python.Some extra might get added or
some might be removed.
 You can also get the list of keywords in your current version by typing the following in
the prompt

VLITS II YEAR STUDENTS &STAFF


PYTHON 19

Description of Keywords in Python with examples


True, False
 True and False are truth values in Python. They are the results of comparison operations
or logical (Boolean) operations in Python.
 True and False in python is same as 1 and 0.

None
None is a special constant in Python that represents the absence of a value or a null
value.It is an object of its own datatype, the NoneType. We cannot create multiple None objects
but can assign it to variables.These variables will be equal to one another.We must take special
care that None does not imply False, 0 or any empty list, dictionary, string etc. Let‘s see an
Example:

and, or , not
and, or, not are the logical operators in Python.and will result into True only if both the
operands are True. The truth table for and is given below:

VLITS II YEAR STUDENTS &STAFF


PYTHON 20

or will result into True if any of the operands is True. The truth table for or is given below:

not operator is used to invert the truth value.The truth table for not is given below:

Example:

as
as is used to create an alias while importing a module. It means giving a different name
(user-defined) to a module while importing it.Let us see the following example:

assert
assert is used for debugging purposes.While programming, sometimes we wish to know
the internal state or check if our assumptions are true.assert helps us do this and find bugs more
conveniently.assert is followed by a condition.If the condition is true, nothing happens. But if the
condition is false, AssertionError is raised.

Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 21

break, continue:
break and continue are used inside for and while loops to alter their normal behaviour.
break will end the smallest loop it is in and control flows to the statement immediately below the
loop.continue causes to end the current iteration of the loop, but not the whole loop.
Example 1:

Example:

class
class is used to define a new user-defined class in python.Class is a collection of related
attributes and methods that try to represent a real world situation.
Example:
class example class:

def
 def is used to define a user-defined function.
Example:
def function_name(parameters):
….…
del: del is used to delete the reference to an object.
Let‘s see an example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 22

if, else, elif


 if, else, elif are used for conditional branching or decision making.
 We should follow indentation while writing these branching statements.
 All lines indented the same amount after the colon(:) will be executed whenever the
boolean expression is true.

Example:

except, raise, try


except, raise, try are used with exceptions in Python.
IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError etc. are few
examples of exception in Python.
Example:

finally
finally is used with try…except block to close up resources or file streams
syntax:
try:
try block
except(exception):
statements 1
finally:
statements 2

VLITS II YEAR STUDENTS &STAFF


PYTHON 23

for
for is used for looping. Generally we use ‗for‘ when we know the number of times we
want to loop.
Example:

import
import keyword is used to import modules into the current namespace.‘from…import‘ is
used to import specific attributes or functions into the current namespace.
Example: import math

global
global is used to declare that a variable inside the function is global (outside the
function).If we need to modify the value of a global variable inside a function, then we must
declare it with global. Otherwise a local variable with that name is created.Example:

in
in is used to test if a sequence (list, tuple, string etc.) contains a value.It returns True if
the value is present, else it returns False. Let us see the following example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 24

is
is used in Python for testing object identity.It returns True if the objects are identical and
False if not.
Example:

lambda
lambda is used to create an anonymous function (function with no name). It is an inline
function that does not contain a return statement.
Usage of lambda functions is explained in detail at concept functions.
Let us see an example

nonlocal
nonlocal is used to declare that a variable inside a nested function (function inside a
function) is not local to it, meaning it lies in the outer inclosing function.
If we need to modify the value of a non-local variable inside a nested function, then we must
declare it with nonlocal.
Otherwise a local variable with that name is created inside the nested function.

VLITS II YEAR STUDENTS &STAFF


PYTHON 25

pass
pass is a null statement in Python. Nothing happens when it is executed. It is used as a
placeholder.
Syntax:
def function(args):
pass

return
return statement is used inside a function to exit it and return a value.If we do not return a
value explicitly, None is returned automatically.
Example:

while
while is used for looping in Python.
Example:

with
with statement is used to wrap the execution of a block of code within methods defined by
the context manager.
Example:

yield
 yield is used inside a function like a return statement. But yield returns a generator.
 Generator is an iterator that generates one item at a time.

VLITS II YEAR STUDENTS &STAFF


PYTHON 26

Python Input- Output


Python provides numerous built-in functions that are readily available to us at the python
prompt.
Some of the functions like input() and print() are widely used for standard input and output
operations respectively.Let us see the output section first
Python output
python output using print( ) function:
 We use the print( ) function to output data to the standard output device(Screen).An
example is given below

In the above print( ) statement , we can notice that a space was added between the string and the
value of variable a.Here are few examples to illustrate this.

 The “sep” separator is used between the values . It defaults into a space character

Output formatting:
 Sometimes we would like to format our output to make it look attractive. This can be
done by using “str.format( )” method. This method is visible to any string object.

Here the curly braces {} are used as “place holders”. We can specify the order in which it is
printed by using numbers.Let us see the following example:

By considering the above example we can say that,first time when we declare the place holder
indices it is reading into memory and then second time when we declare place holder indices it is
writing into memory.
 We can even use keyword arguments to format the string.

VLITS II YEAR STUDENTS &STAFF


PYTHON 27

 We can even format strings like the printf() style used in c programming language. We
use the % operator to accomplish this.

Fancier output formatting:

From above examples,we see without using print( ) statement we can get the output.

Python Input
 Real world programs need to be interactive. With interactive we mean that you need to
take some sort of input or information from the user and work on that input.
 To take input from the users, Python makes use of the input( ) function. The input( )
function prompts the user to provide some information on which the program can work
and give the result.
 But always remember that the input function takes user‘s input as a string.

syntax :
input([prompt])
Where prompt is the string we wish to display on the screen. It is optional.
For inputing values we have two built-in functions input( ) and raw_input( ).But mostly we use
input( ) function for inputing data. The difference is that raw input( ) does not exist in Python
3.x, while input( ) does. Let us see the following example:

Here , we can see that the entered value 10 is a string , not a number . To convert this into a
number we can use int( ) or float( ) functions.

VLITS II YEAR STUDENTS &STAFF


PYTHON 28

Python Indentation
Python uses a different principle called as indentation.
 Whitespace at the beginning of the line is called indentation. In most programming
languages, indentation has no effect on program logic. It is used to align statements to
make the code readable.
 However, in python,indentation is used to associate and group statements.So,Python
programs get structured through indentation. i.e, code blocks are defined by their
indentation.
 In C, we use these whitespace for user readability.In case of python it‘s a language
requirement , not the matter of style.

Same length of indentation is followed in a code block.This principle makes it easier to


read and understand others people python code.
Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 29

QUESTIONS:
2 marks:
1.Write any 4 needs of python programming .
2.Write any 4 applications of python programming .
3.Why python is fast when compared to ‗c‘ and other languages ?
4.What are technical applications of python programming?
5.What are the scientific and numeric applications of python programming?
6.What are the two modes of doing python programming?
7.What is ‗REPL‘ shell ?
8.How can you run the python scripts ?
9.What is variable and how can we declare a variable?
10.Can we do multiple assignments in python ?specify the reason.
11.How can we re-declare a variable ?
12.What is the difference between local and global variables ?
13.What is the concatenation of variables? give examples.
14.What is an identifier ?
15.Define keywords .
16.What is python indentation?
18.Write ways to give input to system in python .
19.Is python case-sensitive ?If yes justify your answer.

7 marks:
1.Write brief notes on history of python .
2.What is the need of python programming ? Explain in detail.
3.Write applications of python programming .
4.Write basics of python programming using ‗REPL‘ shell .
Or
What are the two modes of doing python programming ?Explain in detail.
5.What are the ways of running python scripts ? Explain in detail .
6.What are variables ? Explain.
a)declaration of variable

VLITS II YEAR STUDENTS &STAFF


PYTHON 30

b)re-declaring a variable
c)concatenation of variables
d)local and global variables
e)deleting a variable
7.Write about keywords in python ?
8.What is python indentation ? Explain in detail with example.
9.Write about python input and output statements ?

VLITS II YEAR STUDENTS &STAFF


PYTHON 31

TYPES,OPERATORS AND EXPRESSIONS


 TYPES-integers,strings,Booleans
 OPERATORS-arithmetic operators
-logical operators
-relational or comparision operators
-assignment operators
-bitwise operators
-membership operators
-identity operators
 Expressions and order of evaluations
 Control flow-if
-if-elif-else
-for
-while
-break
-continue
-pass

VLITS II YEAR STUDENTS &STAFF


PYTHON 32

2.TYPES ,OPERATORS AND EXPRESSIONS

The data stored in memory can be of many types.Every value in python has a datatype
but you don‘t need to declare the datatype of variables. How does that work? Based on each
variable‘s original assignment, Python figures out what type it is and keeps tracks of that
internally.
Because everything in python is a object in python.Data types are actually classes and
variables are instants or objects of these class.Python also provides built in datatypes.
For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.

Types
Python has five standard data types(native data types) −
 Numbers
 String
 List
 Tuple
 Dictionary

Python numbers
Python has built in numeric types.Number data types store numeric values. Number
objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types –
 int (signed integers) or plain integers.
 long (long integers ,they can also be represented in octal and hexadecimal).
 float(floating point real values).
 Complex (complex numbers)

int (signed integers): They are often called just integers or ints, are positive or negative whole
numbers with no decimal point.
long (long integers ): Also called longs, they are integers of unlimited size, written like integers
and followed by an uppercase or lowercase L.

VLITS II YEAR STUDENTS &STAFF


PYTHON 33

float (floating point real values) : Also called floats, they represent real numbers and are
written with a decimal point dividing the integer and fractional parts. Floats may also be in
scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number). The real part of the number is
a, and the imaginary part is b. Complex numbers are not used much in Python programming.
Here are some examples of numbers –

In addition, Booleans are a subtype of plain integers. Plain integers are implemented
using long in C, which gives them at least 32 bits of precision. Long integers have unlimited
precision. Floating point numbers are implemented using double in C.
There is an little bit of terminology. when we say ―int‖ it mean the language tyoe
int,when we say ―integer‖ it mean any value that has a mathematical value that is an integer.
Ex:7 is an int,it is also a integer.7.0 is an integer but it is not an int ,it is a float number.
 int,float,long,complex types are called as immutable types(content of the object cannot be
changed after they are created).
 Python supports integers and floats .There‘s no type declaration to distinguish them;
Python tells them apart by the presence or absence of a decimal point..
 Python allows you to use a lowercase l with long, but it is recommended that you use only
an uppercase L to avoid confusion with the number 1. Python displays long integers with

VLITS II YEAR STUDENTS &STAFF


PYTHON 34

an uppercase L. Integer literals with an "L" or "l" suffix yield long integers ("L" is
preferred because "1l" looks too much like eleven!).
 Complex numbers have a real and imaginary part, which are each implemented
using double in C.
 A complex number consists of an ordered pair of real floating-point numbers denoted by
x + yj, where x and y are the real numbers and j is the imaginary unit.

How does python recognize a numeric type?


It does so by storing the type as well as the value and keeping an index to it that includes
a count of the number of active references to it. The variable name is used to point to the variable
and in fact the variable exists completely independent of the variable name.

type( ) and isinstance( )

 You can use the type( ) function to check the type of any value or variable.
 Similarly, you can use the isinstance( ) function to check whether a value or variable
is of a given type.
 Adding an int to an int yields an int.
 Adding an int to a float yields a float.
 Python coerces the int into a float to perform the addition, then returns a float as
the result.

Number Type Conversion (Converting between Types)


Python converts numbers internally in an expression containing mixed types to a common
type for evaluation. But sometimes, you need to coerce a number explicitly from one type to
another to satisfy the requirements of an operator or function parameter.
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and imaginary part
zero.
 Type complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions

Coercing integers to floats and vice-versa:


As you just saw, some operators (like addition) will coerce integers to floating point
numbers as needed. You can also coerce them by yourself.

VLITS II YEAR STUDENTS &STAFF


PYTHON 35

when a binary arithmetic operator has operands of different numeric types, the operand with the
``narrower'' type is widened to that of the other, where plain integer is narrower than long integer
is narrower than floating point is narrower than complex. Comparisons between numbers of
mixed type use the same rule.
The constructors int( ), long( ), float( ), and complex( ) can be used to produce numbers of a
specific type.int → Long → float → Complex. The farther to the right you go, the higher the
precedence.Let‘s see the following program for better understanding.

 you can explicitly coerce a int to a float by calling the float( ) function.
 Unsurprisingly,you can also coerce a float to an int by calling int( ).
 The int( ) function will truncate,not round.
 The int( ) function truncates negative numbers towards 0.Its a true truncate function,not a
floor function.
 Floating point numbers are accurate to 15 decimal places.
 Integers are arbitrarily large.
We can also convert a numeric datatype to a string datatype by using str() function.Many Python
functions are sensitive to the type of data. For example, you cannot concatenate a string with an
integer:

Therefore, you will often find yourself needing to convert one data type to another. Luckily,
conversion functions are easy to remember: the type names double up as a conversion function.
Thus, str() is the function that converts an integer, a list, etc. to a string, and list() is the function
that converts something into the list type. For the example above, you would need
the str() conversion function:

We cannot covert a string into an integer or float or any numeric data type.

VLITS II YEAR STUDENTS &STAFF


PYTHON 36

For ex:

i.e, a string cannot be converted into a numeric data type but a numeric data can be converted to
a string.
Below is a table of the conversion functions in Python and their examples.

Function Converting what to what Example


int( ) String,floating point to integer >>>int(―2014‖)
2014
>>>int(3.14159)
3
float( ) Srting,integer to Floating point number >>>float(‗1.99‘)
1.999
>>>float(5)
5.0
str( ) Integer,floating point to String >>>str(3.141459)
‗3.141592‘
>>>str(1345)
‗1345‘

Strings
Strings are amongst most popular types in python. we can create them simply by
enclosing characters in quotes. Python treats single quotes same as double quotes. creating
strings is as same as creating variables.
Ex: str = ‗python‘
Some important points in strings are

 String is a sequence of Unicode characters.


 String index starts with zero.
 String name itself is an address. Python interpreter reads from this address.
 String object does not support item assignment and item deletion.
 Strings are immutable.
 There is no need of writing data type str in programs when we are using or accessing
strings.
There is a flexibility in python that is we can check the data type of a variable by using a
predefined function called ‗type ( )‘ .There is another flexibility in python we can check whether
the given variable is a string variable or not by a predefined function known as ‗isinstance ( )‘:

VLITS II YEAR STUDENTS &STAFF


PYTHON 37

Accessing values in strings


We can access a single character or group of characters known as substrings by using
the square brackets for slicing along with the index or indices to obtain our substring.

Memory diagram for string ‗str‘

0 1 2 3 4 5 6 7 8
p r o g r a m i z
-9 -8 -7 -6 -5 -4 -3 -2 -1

This is the way how we can access strings. Few points are:
 We can access group of characters from one particular index to another index as our
requirement as mentioned in above example.
 We can also access or print whole string by using square braces by inserting shift colon
that is (:) in between the braces as shown above.
 We can also access the strings using negative indices also.
 We can access in forward direction only. We cannot access or print the characters in
reverse direction.

Accessing using negative indices


To understand the following examples refer to the memory diagram of str:
We cannot access group of character in reverse direction in a string as we seen in below example
[-2:5] is not possible, but we can print whole string in reverse direction.

VLITS II YEAR STUDENTS &STAFF


PYTHON 38

Updating strings
We can update the existing string by reassigning the variable to another string or we can update
the string by concatenating another string to previous string using plus sign. Let us see the
following example:

This is also an another way of updating the string

String special operators


Assume string variable a holds ‗hello‘ and b holds ‗python‘, then:

Operator Description Example

+ Concatenation - Adds values on either side of the a+b will give


operator HelloPython

* Repetition - Creates new strings, concatenating a*2 will give


multiple copies of the same string HelloHello

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range

In Membership - Returns true if a character exists in „h‟ in a will give


the given string True

not in Membership - Returns true if a character does not „m‟ not in a will
exist in the given string give True

VLITS II YEAR STUDENTS &STAFF


PYTHON 39

String formatting operator


One of Python's coolest features is the string format operator %. This operator is unique to
strings and makes up for the pack of having functions from C's printf( ) family. Following is a
simple example –

.Here %s and %d are called as format specifiers.


Replacing characters in string:
 We can replace a character or group of characters in strings.
 Replacing particular index is not directly possible in python but we can use lists to
replace a particular index.
 We can replace group of characters by using a predefined function called replace( )

Replacing group of characters:


Here we use a function called replace().let us see the following example

In above code all ‗ is‘ in the str variable is replaced with ‗was ‗.
Another way is:

In the above code only 2 times the ‗is‘ was replaced with ‗was‘ from left to right because we
given 2 in the braces .

Replacing particular index:

Here we use lists to replace one particular index. Let us consider the following example:

Here we have assigned ‗s‘ as a list. if we try to print ‗s‘ it prints in the form of list. Now
we have replaced s[1] means ‗y‘ with ‗k‘ by using assignment operator. Then we print‗s‘ now it
prints as ‗pkthon‘. this is called replacement .If we want to print replaced string then we use the
function called join( ) to print the new string.

VLITS II YEAR STUDENTS &STAFF


PYTHON 40

Triple quotes
Python triple quotes are used to print the multiple lines including verbatim newlines, tabs and
any other special operator. The syntax for triple quotes consists of three consecutive single or
double quotes.Let‘s see an example.

Deleting strings
 We cannot delete a single character or group of characters from a string.
 If we want to delete we can delete entire string. It is possible by using a keyword called
‗del‘.String objects does not support item deletion.If we are deleting the strings then we
are deleting the memory allocated to that string variable.

Boolean data types


To implement Boolean data type there is a keyword called ‗bool‘ in ‗c‘ .In python we
have 2 values for Boolean type that is (True & False)

VLITS II YEAR STUDENTS &STAFF


PYTHON 41

Boolean values with logical operators


 The 3 main logical operators are [and, or, not].
 We can use Boolean values and do operations with these logical operators.
 and will result true if both operand are true.
 or will result true if any of the operand is true. not is used to invert the truth table.

Boolean data type with „and‟ operator


A B A and B
True True True
True False False
False True False
False False False
Boolean data type with „or‟ operator
A B A or B
True True True
True False True
False False True
False False False
Boolean data type with „not‟ operator
A not A
True False
False True

Operators
Mostly following types of operators exist in python.
 Arithmetic operators
 Logical operators
 Relational or comparision operators
 Assignment operators
 Bitwise operators
 Identity operators
 Membership operators

Arithmetic operators
Syntax : Operand1(arithmetic operator)operand2
The following is the table showing arithmetic operators in python.

VLITS II YEAR STUDENTS &STAFF


PYTHON 42

Operator Description Example


(+) Addition It adds values on either side of the a = 10
operator. b = 20
a+b = 30
(-) subtraction It subtracts right hand operand from left a=10
hand operand b=20
a-b =-10
(*)Multiplication It multiplies values on either side of the a=10
operator b=20
a*b =200
(/)Division It divides left hand operand by right hand a=10
operand b=20
a/b=0.5(or)if b/a=2
(%)Modulus Divides left hand operand to right hand a=10
operand and returns ―remainder‖ b=20
b% a=0
(**)Exponent It performs exponential calculations on a=10
operator b=20
a**b =1020
(//)Floor division Division of operands results quotient in a=10
which digits after decimal are removed if b=20
one of the operands is negative the result 9//2=4
is floored.

Let‘s see an example on arithmetic operators.

VLITS II YEAR STUDENTS &STAFF


PYTHON 43

Output:

 The new two arithmetic operators in python are floor division and exponent.
 These operators made our work more simpler in mathematics when compared to other
languages like ‗c‘,‘java‘..
 This tells that python interpreter is more convenient than ‗c‘ compiler.

Logical operators
Python is case sensitive for logical operators.

Operators Description Example


and Both the operands are true 10 and 5
(logical and) then condition is true o/p: True

or If any of the two operands 10 or 0


(logical or) are non zero then the o/p: True
condition becomes true
not (logical not) Used to reverse the logical 10 not 6
state of its operand o/p: True

Let us see another example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 44

Comparision operators
Following table holds a=10 and b=20

Operator Description Example


Equal to : it the values of two
operands are equal, then the condition
becomes true. a == b
==
False

Not equal to : if value of two


operands are not equal ,then the a != b
!= condition becomes true. True

If value of two operands are not


equal, then the condition becomes
a <> b
<> true .
True
(this operator is similar to !=
operator)
Greater than:if the value of left
operand is greater than the value of
right operand, then the condition a > b
> becomes true. False

Less than : if the value of left


operand is less than the value of a < b
< right operand , then the condition True
becomes true.
Greater than or equal to: if the value
of left operand is greater than or
equal to the value of right operand , a >= b
>= then the condition becomes true. False

Less than or equal to: if the value of


left operand is less than or equal to
the value of right operand , then the a <= b
<= condition becomes true. True

 Comparision operators compares two values


 The output is a boolean expression.

VLITS II YEAR STUDENTS &STAFF


PYTHON 45

Example:

Output:

Assignment operators
 The basic property of assignment operator is left side should be a variable and right side
it may be a variable or a constant.
 Assignment operators are used in python to assign values to variables.Assume variable a
holds 10and variable b holds 20.

Following are the comparision operators:

Operator Description Example


= Assigning operator: Assigns values from right side c=a+b
operands to left side operand
+= Add AND: It adds right operand to the left operand and c+=a
assign the result to left operand .

VLITS II YEAR STUDENTS &STAFF


PYTHON 46

SubtractAND:It subtracts right operand from the left


-= c-=a
operand and assign the result to the left operand.

MultiplyAND:it multiplies right operand to the left c*=a


*= operand and assign the result to left operand.

Divide AND: it divides right operand with the left c/=a


/= operand and assigns the result to left operator.

Modulus AND:It divides right operand with the left


operand and assigns the remainder as a result to left c%=a
%=
operand.

ExponentialAND: Performs exponential caluculation c**=a


**= and assign result to left operand.
Floor Divison AND: the divison of operands where the
result is the quotient in which the digits after the decimal c//=a
//=
points are removed.

Example:

output:

VLITS II YEAR STUDENTS &STAFF


PYTHON 47

Bitwise Operators
 Bitwise operators act on operands as if they were string of binary digits.
 It operates “bit by bit” , hence the name Bitwise.
Assume variable a holds 60 and variable b holds 30.
a=60

b=13

The following table illustrates the usage of bitwise operators.


Operator Description Example
Binary AND: results True if both operands
& a&b
are non zero bits.
Binary OR: it results True if either one of the
| a|b
operand is non zero bit.
Binary Exclusive OR:it results False if both
^ a^b
operands are same.
Binary One‘s Complement : It is unary and
~ ~a
has the effect of ―flipping‖ bits.
Binary left shift/right shift : the left operand
<< , >> value is moved left/right by the number of a<<2 and a>>2
bits specified by the right. operand.

Example :

Output:

VLITS II YEAR STUDENTS &STAFF


PYTHON 48

Memory allocation for Binary AND ( &) :

Memory allocation for Binary OR ( | ):

Memory allocation for Binary Exclusive OR (^):

Memory allocation for Binary Left shift (<<):

Memory allocation for Binary right shift (>>):

Memory allocation for Binary ones complement ( ~) :

One‘s complement for above example:

For a we have to find two‘s complement then the answer is

Membership Operators
Python provides a new operator that is membership operators.
 in and not in are the membership operators in python .
 They are used to test whether a value or variable is found in a sequence.
 The result of membership operators is a boolean value.
 If we want to write membership operators we need to use conditional statements.
 These conditional statement is called a boolean expression.

Operator Description Example


in Evaluates to True if it finds a X in Y ,here in results the
variable in the specified sequence value of this expression is
and False otherwise. True if X is a member of
sequence Y
not in Evaluates to True if it does not find a X not in Y, this expression
variable in the specified sequence results True if X is not in
and False otherwise. member of sequence Y

VLITS II YEAR STUDENTS &STAFF


PYTHON 49

Ex:

output:

Identity operators
 is and is not are the identity operators in python.They are used to check if two values
are located on the same part of the memory.If we want to write identity operator we need
to use a conditional statement.
The following is are the identity operators:
Operator Description Example
Evaluates to true , if in the variables on either side of the x is y
is
operator point to the same object and false otherwise. results True if x=y
Evaluates to false , if in the variable on either side of the x is not y
is not operator point to the same object and true otherwise results True if x !=y

Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 50

output :

Expressions
An expression is a combination of values, variables, operators and calls to functions.
 Expressions need to be evaluated .
 If you ask python to print an expression , the interpreter evaluates an expression and
displays the result.
 An expression should be legal i.e., it should follow the rules of interpreter that depends
on the length. These rules varies from language to language.
 There exists both valid and invalid expressions.
Valid expression : a=2, Invalid expression : 2=a
In order to get the expected output the interpreter should follow some order of evaluating
expressions.

According to the interpreter the first priority is given to right side expression.And then among
the operations of addition and multiplication the highest priority goes to the multiplication [*]
such that it performs first.

Order of evaluations
Python evaluates expressions from left to right. Notice that while evaluating an
assignment, the right hand side is evaluated before the left hand side.
Operator precedence

** Exponential operator
!, +, - Complement, unary plus, unary minus
*, \, %, // Multiplication,division,modulus,floor division operators
+, - Addition, subtraction operators
<<, >> Left shift, right shift operators
& Bitwise AND operator
^, | Exclusive OR, OR operator
< =, > =, < > Comparision operators
= =, !=, < > Equal to, not equal to, less than, greater than operators

=, %=, /=, +=, -=, *=, **= Assignment operators


is, is not Identity operators
in, not in Membership operators
Or, not, and Logical operators

VLITS II YEAR STUDENTS &STAFF


PYTHON 51

 When two operators are having the same priority then the order of evaluation of that
expression moves from left to right.Note that there is an exceptional case that the
exponential operator has an order of evaluation from right to left.

 In above program in each case of print(e) statement the value of ‗e‘ is getting updated
inside the memory.

Control flow
Python supports many conditional and branching statements.

if statement
syntax-
if Boolean expression:
statements

A few more statements about if statement:


 The colon[:] is significantly required, it separates the header of the compound statements
from the body.
 The line after the colon[:] must be indented, it is standard in python to use minimum of
four spaces for indenting.
 All lines indented the same amount after the colon[:] will be executed when the Boolean
expression is true.
Flowchart representation of if statement

VLITS II YEAR STUDENTS &STAFF


PYTHON 52

Example:

if- else statement


It is frequently the case that you want one thing to happen when a condition is true, and
something else to happen when it is false.For that purpose we use if else statement.
Syntax:

Flow chart of if else statement

Example

if-elif-else statement
syntax:
if (boolean expression 1):
Statements_1
elif(boolean expression 2):
Statements_2
else:
Statements_3

VLITS II YEAR STUDENTS &STAFF


PYTHON 53

Flow chart of if-elif-else statement

 The elif is short for else if. It allows us to check for multiple expressions.
 If the condition for if is False, it checks the condition of the next elif block and so on.
 If all the conditions are False, body of else is executed.
 Only one block among the several if...elif...else blocks is executed according to the
condition.

Nested if statement
Syntax:

VLITS II YEAR STUDENTS &STAFF


PYTHON 54

We can have an if-elif-else statement inside another if-elif-else statement. This is called
nesting in computer programming.Any number of these statements can be nested inside one
another.Indentation is the only way to figure out the level of nesting.

Example:

for loop conditional statement


 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
 We can write a program without using a for loop.But it takes more lines of code and
occupies more space in the memory.Hence we use for loop

Syntax and flowchart:

for loopvariable in sequence:


statements

VLITS II YEAR STUDENTS &STAFF


PYTHON 55

Example:

(ii)To check whether the given number is Prime number or not program using for loop

while statement
 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
 We generally use this loop when we don't know beforehand, the number of times to
iterate.

VLITS II YEAR STUDENTS &STAFF


PYTHON 56

Syntax:
while (Boolean _expression):
statements
Flowchart of while loop:

In while loop, boolean expression is checked first. The body of the loop is entered only if
the Boolean expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the Boolean expression evaluates to False.
 In Python, the body of the while loop is determined through indentation.Body starts with
indentation and the first unindented line marks the end.
 Python interprets any non-zero value as True. None and 0 are interpreted as False.
 We can write a while loop code for every ‗for‘ loop logic.
Example:
Here in this example, we are going to enter a string so that string matches to the already defined
string.But if it doesnot match to the string we are going to give a hint such as giving first letter of
string and if it doesn‘t match again giving next letter in the string.

VLITS II YEAR STUDENTS &STAFF


PYTHON 57

break statement
 break statement changes the direction of interpreter.
 The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
 If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.
Syntax and Flowchart of break :
break

continue statement
Similar to break statement the continue statement also changes the direction of interpreter.
Syntax and flowchart
Continue

VLITS II YEAR STUDENTS &STAFF


PYTHON 58

pass statement
In python programming pass is a null statement.The difference between a comment and
pass statement is that while the interpreter ignores a comment completely and pass is not
ignored.

A few more points regarding pass statement:


 It results in no operation.
 We generally use it as a placeholder.
 Suppose we have a loop or a function that is not implemented but we want to implement
it in future. They cannot have an empty body. Such that the interpreter would complain.
 So that the pass statement is useful to construct a body that does nothing.

VLITS II YEAR STUDENTS &STAFF


PYTHON 59

Flow chart representation of pass statement

Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 60

QUESTIONS
2 marks:
1.List out the various operators supported in python.
2.Write a short note on data type in python.
3.Python variables do not have specific types. Justify this statement with help of examples.
4.What is slicing operator ?how can you extract a substring from a given string ?
5.Differentiate between ―=‖ and ―==‖ ?
6.Write about type( ) and is instance( ) functions with examples.
7.Is strings are mutable ? justify your answer with example.
8.What is item – assignment ?
9.How we can write subjects to strings ?
10.Why ‗*‘ is called string repetition opertator ? give an example
11.How can we delete a string ?
12.Write about string – formating operator ?
13.How to reverse a string ?
14.Write briefly about ‗**‘nand ‗//‘ operator with example ?
15.Write a short note on ― < >‖ operator.
16.How memory is organized in case of ‗-ve‘ numbers ?
17.Explain bitwise left shift and right shift operators.
18.Explain logical operators.
19.What are membership operators ?
20.Explain about identity operators ?
21.Explain about identity operators ?
22.Which operators are given least and highest precedence ?
23.What are expressions in python ?
24.Differentiate between ‗break‘ and ‗continue‘ ?
25.Differentitate comment and pass statements in python.
26.Write about python operator precedence ?
27.What is the difference between defining boolean data types in c and python.

VLITS II YEAR STUDENTS &STAFF


PYTHON 61

7 marks
1.Explain different datatypes in python.
2.Write briefly about strings and explain
a) creating strings
b)updating strings
c)accessing strings
d)deleting string with example.
3.What are the various operators in python ? explain briefly about each operator with examples.
4.Write a note on if , elif, for, while,with examples ?
5.Discuss briefly about break,continue and pass.
6.Explain expessions and order of evaluation of expressions with an example.

VLITS II YEAR STUDENTS &STAFF


PYTHON 62

Data structures
 Lists-operations,slicing,methods
 Tuples
 Sets
 Dictionaries
 Sequences
 Comprehensions

VLITS II YEAR STUDENTS &STAFF


PYTHON 63

3.DATA STRUCTURES
The design and analysis of efficient data structures has long been recognized as a vital
subject in computing and is part of the core curriculum of computer science and computer
engineering undergraduate degrees. Data Structures in Python provides an introduction to data
structures including their design, analysis, and implementation.
Data structures are basically just that - they are structures which can hold some data together.
In other words, they are used to store a collection of related data.

Characteristics of a data structure


 Correctness − Data structure implementation should implement its interface correctly.
 Time Complexity − Running time or the execution time of operations of data structure
must be as small as possible.
 Space Complexity − Memory usage of a data structure operation should be as little as
possible.

Need for data structure


As applications are getting complex and data rich, there are three common problems that
applications face now-a-days.
 Data Search − Consider an inventory of 1 million(106) items of a store. If the
application is to search an item, it has to search an item in 1 million(106) items every
time slowing down the search. As data grows, search will become slower.
 Processor speed − Processor speed although being very high, falls limited if the data
grows to billion records.
 Multiple requests − As thousands of users can search data simultaneously on a web
server, even the fast server fails while searching the data.
To solve the above-mentioned problems, data structures come to rescue. Data can be organized
in a data structure in such a way that all items may not be required to be searched, and the
required data can be searched almost instantly.

Python data structures


Data structure is a programming way which helps us to organize the memory in
efficient way.
 By using data structure concept called as sequence python has 6 built in type of data
structures.They are:
1.Lists
2.Tuples
3.Sets
4.Dictionaries
5.Comprehensions
6.Sequences
 The most common ones are lists and tuples.
 Each element of sequence is assigned to number i.e its position or index.
 Any sequence index starts with zero.
 Lists and Tuples are sequences but dictionaries,sets are not sequences.

VLITS II YEAR STUDENTS &STAFF


PYTHON 64

Lists
 Lists are Python‘s workhorse datatype.
 The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets.
 Important thing about a list is that items in a list need not be of the same type.
 List index starts with zero.
 Lists are mutable.
 If there are two same elements in list it considers as two distinct elements and stores in
memory with different index.

Creating lists
Creating a list is as simple as putting different comma-separated values between square brackets.
We can create list in 2 ways:

Assigning values to variable


This is as simple as creating variables. The following example illustrates creating lists.

Using list( )
This function creates a list from an iterable object. An iterable may be either a
sequence, a container that supports iteration, or an iterator object. If no parameters are specified
,a new empty list is created.

Accessing values in lists


To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index. Few important points are
 we can access a single element in list by simply using its index.

VLITS II YEAR STUDENTS &STAFF


PYTHON 65

 We can access group of elements by slicing using ‗:‘ symbol.


 We can access through negative indices also but accessing mast be done in forward
direction only, else it gives empty list.

Example:
list1=[1,2,3,4,5,6,7,8,9].
Memory diagram for list1:

Accessing strings in a list


Let‘s take a string ‗python‘ as an element in a list .
 In the following example, ‗python‘ is stored at index 0.
 To access a single character in this python string, interpreter provides a facility of using
[ ][ ].
 The first parenthesis is to access element in a particular index.
 Second parenthesis is to access characters or letters or sub elements in that list.

VLITS II YEAR STUDENTS &STAFF


PYTHON 66

Updating lists
Since lists are mutable we can update defined lists and their elements.
 In ‗c‘ it is very tough to append values to a list.
 Updation can be done in four ways:
1.using append( ) method.
2.updating group of elements in list through slicing.
3.updating a single character using [ ].
4.updating whole list.

Let us consider the following example:

k=[1,2,3,4,5,6,7]

Using append( )
Syntax:
list name.append(argument)

Consider k=[1,2,3,4,5,6,7]

VLITS II YEAR STUDENTS &STAFF


PYTHON 67

Now the memory diagram of k changes to

Updating group of elements


We can update sequence of elements of a list in the following way:

Now what happens is the values which are stored at k[1],k[2],k[3] i.e 2,3,4 are updated with
7,8,9
The memory looks as follows:

Updating single element


we can update a single character using its index as follows:

Now the value which is stored at index 2 in the memory changes from 3 to 5.

Updating whole list


By giving or assigning all different values to the list we can update the whole list:
Let us see the following example:

Deleting lists
Since lists are mutable we can perform deletion operation on them.We use ‗del‘ keyword to
delete a list. It can be done in 3 ways:
1. deleting single character using remove( ) function or simply using its index preceeding by
keyword del.
2. deleting sequence of characters.
3. deleting whole list.

VLITS II YEAR STUDENTS &STAFF


PYTHON 68

Deleting single character

Consider k=[1,7,8,9,5,6,7,20] .Memory diagram looks as follows:

Here the value which is stored at index 2 i.e 8 is deleted and in place of memory which is
allocated to index 2 is replaced by the next value i.e 9.
Now the memory looks as follows:

We can do it another way using remove( ). But here we will not use index we refer the element
in the list.

Deleting sequence of characters

We can delete sequence of characters using slicing i.e [ ]


Consider k=[1,7,9,5,6,7,20]

Here what happens is after deleting the values which are stored at k[1],k[2],k[3] i.e 7,9,5 the
memory allocated to these indices are replaced by the values 6,7,20
Memory diagram as follows:

VLITS II YEAR STUDENTS &STAFF


PYTHON 69

Deleting whole list


We can delete whole list simply by using keyword ‗del‘ and followed by list name.
After deleting the list if we are trying to access it then it will show an error i.e name ‗listname‘
not defined.

Converting string into list


To convert string into list we simply use list( ) or split( ).

Using list( )

Using split( ) method

Syntax:
variable.split( )

Differences between lists and strings in python


 One simple difference between strings and lists is that lists can be any type of data i.e.
integers, characters, strings etc. while strings can only hold a set of characters.
 Strings does not support item assignment while lists support item assignment.
 Lists are mutable where strings are immutable
 Strings can be created by single or double quotes whereas list is created by using [ ]
brackets in which elements in the list are separated by using commas.

VLITS II YEAR STUDENTS &STAFF


PYTHON 70

List operations
There exits several operation on lists. Few operations are explained below.

VLITS II YEAR STUDENTS &STAFF


PYTHON 71

Let‘s see the following example:

List methods
 Python has various methods to help programmers work efficiently with lists.
 Some of these methods are summarized in below table

Method Description syntax Example output


append( ) Adds an item to the list.append(obj) x=[‗h‘,‘e‘,‘l‘,‘l‘,‘‘o‘] [‗h‘,‘e‘,‘l‘,
end of the list. x.append(-2) ‗l‘,‘o‘,-2]
print(x)

count( ) counts the number of list.count(obj) x=[‗h‘,‘e‘,‘l‘,‘l‘,‘o] 2


times an element print(x. count(‗l‘))
appears in the list.
index( ) Returns the index of list.index(obj) list=[6,4,7,1,3,9,5,0] 2
the first matched item. print(list.index(7))

pop( ) Removes and returns list.pop(index) list.pop(3 ) 1


an element at the given print(list) [6,4,7,3,9,5,
index (consider above list) 0]

remove( ) Removes an element list.remove(obj) list.remove(4) [6,1,3,9,5,0]


from the list. print(list)

VLITS II YEAR STUDENTS &STAFF


PYTHON 72

reverse( ) Reverse the element in list.reverse(obj) list.reverse( ) [0,5,9,3,1,6]


the list. print(list)

sort( ) Sorts the element in list.sort( ) list=[6,1,3,9,5,0] [0,1,3,5,6,9]


the list. list.sort( )
print(list)

extend( ) Add all elements list1.extend(list2) x=[1,2,3] [1,2,3,4,5,6]


of a list to the another y=[4,5,6]
list. x.extend(y)
print(x)

 insert( ) , remove( ) and sort( ) methods only modify the list and do not return any value.
 If you print the return values of these methods , you will get None.
 This is a design principle that is applicable to all mutable data structures in python.
 When one list is assigned to another list using the assignment operator ( = ),
then a new copy of the list is not made.

 Instead ,assignment makes the two variables point to the one list in memory.
This is also called as aliasing.

The code given below illustrates this point

VLITS II YEAR STUDENTS &STAFF


PYTHON 73

Slicing in python
 The slice object is used to slice a given sequence( string,tuple,list or range)or any object
which supports sequence protocol.
 Slice object represents the indices specified by range(start,stop,step) .

Syntax :
slice(stop) : variable_name[start::] from start to end (start can be any index)
variable_name[::stop] from start to stop (stop can be any index)
slice(start,stop,step): variable_name[start:stop:step] from start to stop with difference of step.
(refer accessing list values).

Tuples
In python, tuples are a part of standard language .A tuple is a sequence of immutable
Python objects. Tuples are sequences, just like lists. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas in a list, elements can be
changed .So, tuples are immutable i.e we cannot add, change, or delete elements from the tuple.
Syntax:
tuple_name=(element1,element2,element3)
 A tuple is defined in the same way as a list, except that the whole set of elements is
enclosed in parenthesis instead of square brackets.
 The elements of a tuple have a defined order,just like a list.Tuples indices are zero based
,just like a list, so the first element of a non empty tuple is always t[0].
 Negative indices count from the end of the tuple just as with a list.
 Slicing works too, just like a list.Note that when you slice a list, you get a new list; when
you slice a tuple you get a new tuple.
 Tuples have many operations .Tuples have no methods like as list.

Constructing or creating tuples


Creating a tuple is as simple as putting different comma-separated values. Optionally you
can put these comma-separated values between parentheses also. For example,
To create a tuple, place values within brackets:
>>> l = (1, 2, 3)

VLITS II YEAR STUDENTS &STAFF


PYTHON 74

It is also possible to create a tuple without parentheses, by using commas:

If you want to create a tuple with a single element it is a bit tricky, you must use the comma:

You can repeat a tuples by multiplying a tuple by a number:

Note that you can concatenate tuples and use augmented assigenment (*=, +=):
>>> s1 = (1,0)
>>> s1 += (1,)
>>> s1
(1, 0, 1)

The empty tuple is written as two parentheses containing nothing _


tup1 = ( )

Accessing values in tuples


To access values in tuple , use the square brackets for slicing along with the index or
indices to obtain value available at that index .There are various ways in which we can access the
elements of a tuple. Python has tuple assignment feature which enables you to assign more than
one variable at a time.
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 index from 0 to 5. Trying to access an element
other that (6, 7,...) will raise an IndexError.The index must be an integer, so we cannot use float
or other types. This will result into TypeError.We can access a particular element by indexing.

When the above code is executed, it produces the following result –

Nested Tuples
A tuple can consists other tuples as its elements .This is called as ―nested tuple‖.We
can access the elements of a nested tuple by indexing.

VLITS II YEAR STUDENTS &STAFF


PYTHON 75

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
To fetch specific sets of sub-elements from tuple or list, we use this unique function
called slicing.we can access a range of items in a tuple by using the slicing operator - colon
":".try the below tuple:Let us see the following example.

VLITS II YEAR STUDENTS &STAFF


PYTHON 76

Updating tuples
we can update values of a list, let‘s see the example whether updating is possible in tuples.

 Tuples cannot be updated being immutable.


 Tuples does not support item assignment.
 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 –

Deleting tuple elements


As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple. Removing individual tuple elements is not possible.
There is, of course, nothing wrong with putting together another tuple with the undesired
elements discarded .To explicitly remove an entire tuple, just use the del statement. For
example.

Packing and Unpacking


In packing, we place value into a new tuple while in unpacking we extract those values
back into variables.

VLITS II YEAR STUDENTS &STAFF


PYTHON 77

Tuple Operations
Conversion into a tuple using tuple( ) function
We can convert a list or a sequence into a tuple by using a built-in function called ―tuple‘
which converts a sequence into a tuple.Though ‗tuple‘ is built-in function ,when we use tuple as
variable name it doesnot generates error where in c it is an error to use a built-in function as a
variable name.
Tuples can be converted into lists, and vice-versa. The built-in tuple() function takes
a list and returns a tuple with the same elements, and the list() function takes a tuple and
returns a list. In effect, tuple() freezes a list, and list() thaws a tuple.

Built-in functions with Tuple

To perform different task, tuple allows you to use many built-in functions like all( ),
any( ),enumerate( ), max( ), min( ), sorted( ), len( ), etc.Some other operations like
concatenation, repetition, iteration, membership operation cane be done with tuples.

Following are the basic functions in tuples:

function Description

all( ) Return True if all elements of the tuple are true (or if the tuple is empty).

Return True if any element of the tuple is true. If the tuple is empty,
any( )
return False.

Return an enumerate object. It contains the index and value of all the items of
enumerate( )
tuple as pairs.

VLITS II YEAR STUDENTS &STAFF


PYTHON 78

len( ) Return the length (the number of items) in the tuple.

max( ) Return the largest item in the tuple.

min( ) Return the smallest item in the tuple

Take elements in the tuple and return a new sorted list (does not sort the tuple
sorted( )
itself).

sum( ) Return the sum of all elements in the tuple.

tuple( ) Convert an iterable (list, string, set, dictionary) to a tuple.


cmp( ) Compares elements of two tuples.

Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 79

Note that,all( ) and any( ) takes only one argument.if you give more arguments it generates error.

Methods in tuples
Tuples are immutable, so they have no methods that would allow you to change them.
Lists have methods like append(), extend(), insert(), remove(), and pop(). Tuples have
none of these methods as these methods would change the tuple.. You can slice a tuple (because
that creates a new tuple), and you can check whether a tuple contains a particular value (because
that doesn‘t change the tuple), and that‘s about it.

 You can‘t add elements to a tuple.Tuples have no append( ) or extend( ) method.


 You can‘t remove elements from a tuple.Tuples have no remove( ) or pop( ) method.

There are two methods available that doesnot change the tuple.
 index ( ) method-to find occurrence of a value.
 count( ) method-to count the number of occurrence of a value.

index method( )
using index( ) method,we access the index of a particular index.index( ) method takes exactly
only one argument.

VLITS II YEAR STUDENTS &STAFF


PYTHON 80

count( ) method
count( ) method gives the frequency of a element in the tuple.count( ) takes exactly
only one argument.

Tuples in boolean context


You can use tuples in a Boolean context, such as an if statement.
 In a Boolean context,an empty tuple is false.
 Any tuple with at least one item is true. The value of the items is irrelevant.
But what‘s that comma doing there?
 To create a tuple of one item, you need a comma after the value.
Without the comma, Python just assumes you have an extra pair of parentheses,
which is harmless, but it doesn‘t create a tuple.

VLITS II YEAR STUDENTS &STAFF


PYTHON 81

Tuples are not completely immutable!


If a value within a tuple is mutable, then you can change it:

In the above example, t at the first has a immutable tuple in it and when you try to update,
being immutable it generated error.and at the second tuple t,it has a list as a element.list being
mutable can be updated.

Copy a tuple

To copy a tuple, just use the assignment:

You cannot copy a list with the = sign because lists are mutables. The = sign creates a
reference not a copy. Tuples are immutable therefore a = sign does not create a reference but a
copy as expected.

Convert tuple into a string

You can convert a tuple to a string with either:


>>> str(t)

VLITS II YEAR STUDENTS &STAFF


PYTHON 82

tuples for returning multiple values


In python,we can return multiple values unlike ‗c‘.the below example clearly illustrates it.

Advantages of tuples over lists


Since, tuples are quite similar to lists, both of them are used in similar situations as
well.However, there are certain advantages of implementing a tuple over a list. Below listed are
some of the main advantages:

 Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary. With list,
this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
 The set itself is mutable. We can add or remove items from it.
 Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc..

Syntax:
Set-variable={value1,value2,…..,value n}

Creating sets
 A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set( ).
 It can have any number of items and they may be of different types (integer, float, tuple,
string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its
element.Let us see the following examples:

VLITS II YEAR STUDENTS &STAFF


PYTHON 83

Creating empty set


Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements we use the set() function without any argument.To know this we use type( )
function.Let‘s see the following example.

How to change a set in Python?


 Sets are mutable. But since they are unordered, indexing have no meaning.
 We cannot access or change an element of set using indexing or slicing. Set does not
support it.
 We can add single element using the add( ) method and multiple elements using
the update() method. The update( ) method can take tuples, lists, strings or other sets as
its argument. In all cases, duplicates are avoided.

Error obtained because more arguments are given in update( ) function.

VLITS II YEAR STUDENTS &STAFF


PYTHON 84

Deleting set elements:

 A particular item can be removed from set using methods, discard( ) and remove( ).
 The only difference between the two is that, while using discard( ) if the item does not
exist in the set, it remains unchanged. But remove( ) will raise an error in such condition.

 Similarly, we can remove and return an item using the pop( ) method.
 Set being unordered, there is no way of determining which item will be popped. It is
completely arbitrary.
 We can also remove all items from a set using clear( ).

Python set operations


Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Set Union

VLITS II YEAR STUDENTS &STAFF


PYTHON 85

Union of A and B is a set of all elements from both sets.Union is performed using | operator.
Same can be accomplished using the method union().

Set Intersection

Intersection of A and B is a set of elements that are common in both sets.Intersection is


performed using & operator. Same can be accomplished using the method intersection().

Set Difference

Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B -
A is a set of element in B but not in A.Difference is performed using - operator.Same can be
accomplished using the method difference( ).

Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in both A and B except those that are
common in both.Symmetric difference is performed using ^ operator. Same can be accomplished
using the method symmetric_difference( ).

Set Membership Test


We can test if an item exists in a set or not, using the keyword in.

Iterating Through a Set


Using a for loop, we can iterate though each item in a set.

VLITS II YEAR STUDENTS &STAFF


PYTHON 86

let us see the following example:

Different Python Set Methods

Method Description

add( ) Add an element to a set

clear( ) Remove all elements form a set

copy( ) Return a shallow copy of a set

difference( ) Return the difference of two or more sets as a new set

difference_update( ) Remove all elements of another set from this set

discard( ) Remove an element from set if it is a member. (Do


nothing if the element is not in set)

intersection( ) Return the intersection of two sets as a new set

VLITS II YEAR STUDENTS &STAFF


PYTHON 87

intersection_update( ) Updates set with the intersection of itself & another

isdisjoint( ) Return True if two sets have a null intersection

issubset( ) Return True if another set contains this set

issuperset( ) Return True if this set contains another set

pop( ) Remove and return an arbitary set element.


Raise KeyErrorif the set is empty

remove( ) Remove an element from a set. If the element is not a


member, raise a KeyError

symmetric_difference( ) Return the symmetric difference of two sets as a new set

symmetric_difference_update( ) Update a set with the symmetric difference of itself and


another

union( ) Return the union of sets in a new set

update( ) Update a set with the union of itself and others

Let us see the following example

Built-in Functions with Set:


Built-in functions like all( ),any( ),len( ),max(_),min(),sorted( ),sum( ),enumerate( ) etc..are
commonly used with set to perform different tasks.

VLITS II YEAR STUDENTS &STAFF


PYTHON 88

Function Description

all( ) Return True if all elements of the set are true (or if the set is empty).

Return True if any element of the set is true. If the set is empty,
any( )
return False.

Return an enumerate object. It contains the index and value of all the
enumerate()
items of set as a pair.

len( ) Return the length (the number of items) in the set.

max( ) Return the largest item in the set.

min( ) Return the smallest item in the set.

Return a new sorted list from elements in the set(does not sort the set
sorted( )
itself).

sum( ) Return the sum of all elements in the set.

Let us see the following examples:

Dictionaries
A dictionary is an associative array (also known as hashes). Any key of
the dictionary is associated (or mapped) to a value. The values of a dictionary can be
any Python data type. So dictionaries are unordered key-value-pairs.
In simple,Dictionary is a data structure in which we store values as a pair of key and value.
 Each key is separated from its value by ‗ : ‗ and consecutive items are separated by
commas.
 The entire items in a dictionary are enclosed in a curly brackets.
 Dictionaries are optimized to retrieve values when the key is known.

VLITS II YEAR STUDENTS &STAFF


PYTHON 89

Syntax:
Dictionaryname = {key_1: value_1, key_2: value_2,……key_n:value_n}

Creating a dictionary
We can create dictionary in two ways:
1.using curly braces { }
2.using dict( ) function.
 Dictionary is a set of keys and its associated values.
 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.
Let us see the following example:

Accessing
 To access dictionary elements, you can use the familiar square brackets along with the
key to obtain its value.
 If we attempt to access a data item with a key, which is not part of the dictionary, we get
an error.

VLITS II YEAR STUDENTS &STAFF


PYTHON 90

Updating dictionaries
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry.Let us see the following example:

 When we create d[5]=15 what happens is in memory allocated to ‗d‘ a new key ‗5‘ is
created and the value of 15 is assigned to key 5.
 When we declared d[2]=8 the memory which is allocated to key 2 in which initially 6 is
stored is updated with 8.

Deletion in Dictionaries
 We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
 The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary. All the items can be removed at once using the clear() method.
 We can also use the del keyword to remove individual items or the entire dictionary
itself.

Properties of Dictionary Keys


There are two important points to remember about dictionary keys –
 More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins.
 Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.

VLITS II YEAR STUDENTS &STAFF


PYTHON 91

Let us see the following example:

Other built-in functions are

VLITS II YEAR STUDENTS &STAFF


PYTHON 92

Let us see an example:

Let‘s see another example:

Dictionary Methods
Python includes following dictionary methods –
SN Methods with Description

1 dict.clear( )-Removes all elements of dictionary dict

2 dict.copy( )-Returns a shallow copy of dictionary dict

3 dict.fromkeys( )-Create a new dictionary with keys from seq & values set to value.

4 dict.get(key, default=None)-For key key, returns value or default if key not in dictionary

5 dict.has_key(key)-Returns true if key in dictionary dict, false otherwise

6 dict.items( )-Returns a list of dict‘s (key, value) tuple pairs

VLITS II YEAR STUDENTS &STAFF


PYTHON 93

7 dict.keys( )-Returns list of dictionary dict‘s keys

8 dict.setdefault(key, default=None)-Similar to get(), but will set dict[key]=default if key is


not already in dict

9 dict.update(dict2)-Adds dictionary dict2‘s key-values pairs to dict

10. dict.pop(key,default=None)-removes the item with key and return its value or d.

11 dict.values( )-Returns list of dictionary dict‘s values

12 dict.popitem( )-remove and return arbitary item .raises keyerror if key is not found.

Let us see the following example:

Dictionary Membership Test


We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is
for keys only, not for values.

Iterating through a dictionary


Using a for loop we can iterate though each key in a dictionary.

VLITS II YEAR STUDENTS &STAFF


PYTHON 94

Nested Dictionaries
We can create a nested dictionary in python.It is as follows:

Sequences
A sequence is a data structure which is used to organize the memory efficiently. In
python sequence is the generic term for an ordered set.There are several types of sequences in
python.
 A sequence is a iterable with random access. You can ask for any item of the sequence
without having to consume the items before it. With this property you can build slices,
which give you more than one element at once. A slice can give you a subsequence
:seq[from:until] and every nth item :seq[from:until:nth] list, tuple and str all are
sequences.
 If the access is done via keys instead of integer positions, you have a mapping.
 Thus, dict is the basic mapping.

There are six types of sequences:


1. Strings
2. Unicode strings
3. Lists
4. Tuples
5. Buffers
6. X-range objects
Among them the most commonly used sequence types are: strings, lists, and tuples.

Sequence conversions
There is no implicit conversion between different sequence types, except that plain
strings are converted to Unicode strings if needed. (String conversion is covered in detail
in Unicode.) You can call the built-ins tuple and list with a single argument (any iterable) to get a
new instance of the type you‘re calling, with the same items (in the same order) as in the
argument.
Concatenation and repetition
You can concatenate sequences of the sametype with the + operator.You can multiply a
sequence S by an integer n with the *operator.S*n or n*S is the concatenation of n copies of
S.when n<=0,S*n is an empty sequence of the same type as S.

VLITS II YEAR STUDENTS &STAFF


PYTHON 95

Types of sequences

 Strings:

String literals are written in single or double quotes.


Ex: ―xyz‖ or ‗xyz‘
We also know more about strings like mainly accessing a string, deleting a string,
traversing a string etc…
(refer strings in chapter 2)

 Unicode strings:
These Unicode strings are much like strings, but are specified in the syntax using a
preceding character ‗u‘.
Ex: u ―abc‖ (or)
u‘abc‘

 Lists:
List is a collection of various data type elements. These are constructed with [ ] and
separating items with commas ( , ).
Ex: list = [‗a‘,‘b‘,‘c‘]

 Tuples:
Tuples are constructed by using ( ) and the items are separated by commas ( , ) . we can
also write tuples with or without using parenthesis. But an empty tuple must have an
enclosing parenthesis. A single item tuple must be enclosed with parenthesis preceding
with comma ( , ).
Ex: t = (‗p‘,)

 Buffers:
Buffer objects are not directly supported by python syntax. But they can be created by
calling an in built function naming buffer ( ).
They don‘t support concatenation or repetition.

 X-range objects:
These are similar to buffers in that there is no specific syntax in to create them but they
are created by using the x-range( ).
They don‘t support the operations like slicing, concatenation, and repeatition and also
they don‘t support using of in, notin, min( ), max( ).
Python supports a variety of operations applicable to all sequences, including strings,
lists, and tuples. Some sequence operations apply to all containers (including, for example, sets
and dictionaries, which are not sequences), and some apply to all iterables (meaning ―any object
on which you can loop).

VLITS II YEAR STUDENTS &STAFF


PYTHON 96

The above tabular form consisting of various operations which are supported by most of the
sequence types:

Comprehensions
Comprehensions are constructs that allow sequences to be built from other sequences.
Python 2.0 introduced list comprehensions and Python 3.0 comes with dictionary and set
comprehensions.

List comprehensions
Python supports a concept called list comprehensions. It can be used to construct lists
in a very natural, easy way like a mathematician to do.
 List comprehensions provide a concise way to create lists.

VLITS II YEAR STUDENTS &STAFF


PYTHON 97

 It consists of brackets [ ] containing an expression followed by a for clause, then zero or


more for or if clauses succeeding it.
 The expressions can be anything ,meaning that you can put all kinds of objects in list.
 The list comprehension always returns a result list.
syntax:
[expression for item in list if conditional]
This is equivalent to
for item in list:
if conditional statement:
expressions

The following are the common ways to represent or describe the lists or tuples or sets or vectors
in mathematics.
Ex:
s = {x^2: in {0,1,2,3,4,5,6,7,8,9}}
v = (1,2,4,8,------------4096)
m = {x/x is in s and x even}
In python we can represent above statements as follows:

The advantage of writing this in python is that we don‘t have to remember any special scriptic
syntax.

A list comprehension consists of the following parts:


 An Input Sequence.
 A variable representing members of the input sequence.
 An Optional Predicate expression.
 An Output Expression producing elements of the output list from members of the Input
Sequence that satisfy the predicate.

VLITS II YEAR STUDENTS &STAFF


PYTHON 98

A few examples regarding these list comprehensions :

List comprehensions not only work for numbers but also for strings and also for the combination
of strings and integers too.

Conclusion
 List comprehensions allows us to transform one list or other sequence into a new list.
They provide a concise syntax for compelling this task by limiting our lines of code.
 They follow the mathematical term of set builder notation or set comprehension, so they
may be particularly intuitive to programmers with a mathematical background.
 Though list comprehensions can make our code more succinct, it is important to ensure
that our final code is as readable as possible, so very long single lines of code should be
added to ensure that our code is user friendly.

Set Comprehensions
Set comprehensions allow sets to be constructed using the same principles as list
comprehensions, the only difference is that resulting sequence is a set.
Let us see the following example:

Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.

VLITS II YEAR STUDENTS &STAFF


PYTHON 99

 Dictionary comprehension consists of an expression pair (key: value) followed


by for statement inside curly braces {}.let us see the following example.

VLITS II YEAR STUDENTS &STAFF


PYTHON 100

Functions
 Defining functions
 Calling functions
 Passing arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
 Anonymous functions
 Fruitful functions(functions returning values)
 Scope of the variables in a function-Global and Local variables.
Modules
 Creating modules
 Import statement
 Namespacing

Python packages
 Introduction to PIP
 Installing packages via PIP
 Using python packages

VLITS II YEAR STUDENTS &STAFF


PYTHON 101

4.FUNCTIONS

Introduction
Functions are constructed to structure programs. They are also called as subroutines or
methods or procedures.A function is a block of organized, reusable code that is used to perform a
single, related action.
Functions are a convenient way to divide your code into useful blocks providing better
modularity for your application and a high degree of code reusing and save some time .They are
used to increase readability and reduce complexity.Also functions are a key way to define
interfaces so programmers can share their code.
Usually, functions are of two types:
 built-in-functions: functions that are built into python.
 uer-defined functions :functions that are defined by users themselves.
In Python, function is a group of related statements that perform a specific task.

Built-in Functions
The Python interpreter has a number of functions and types built into it that are always
available. They are listed here in alphabetical order.

User-defined functions
As you already know,Python provides you many inbuilt functions like above functions,but it also
gives freedom to create our own functions. These functions are called user-defined functions.
 In programing terminology, functions aren‘t used, they are called. If necessary ,functions
can take input in the form of parameters and return output.
 Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable .Furthermore,
it avoids repetition and makes code reusable.
 In python,all functions are treated as objects,so it is more flexible when compared to
other high –level languages.

Importance of user-defined functions in Python


In general, developers can write user-defined functions or it can be borrowed as a third-party
library. This also means your own user-defined functions can also be a third-party library for
other users. User-defined functions have certain advantages depending when and how they are
used. Let‘s have a look at the following points:

VLITS II YEAR STUDENTS &STAFF


PYTHON 102

 User-defined functions are reusable code blocks:they only need to be written once,then
they can be used multiple times.They can even be used in other applications too.
 These functions are very useful,from writing common utilities to specific business
logic.These functions can also be modified per requirement.
 The code is usually well organized,easy to maintain and developer friendly,which
means it can support the modular design approach.
 As user-defined functions can be written independently, the tasks of a project can be
distributed for rapid application development.
 A well-defined and thoughtfully written user-defined function can ease the application
development process.
Now that we have a basic understanding of the advantages, let‘s have a look at defining a
function in Python.

Defining functions (user-defined functions)


we can define functions to provide the required functionality. The difference between
defining functions in C and python are while passing arguments,we define datatype before each
argument in C ,but in python we don‘t need to mention any datatype while passing
arguments.Python interpreter automatically recognizes variable datatype when the value is
aasigned to that variable.For more reference,refer variables concept.

Rules to define a function in Python

Step 1: Declare the function with the keyword def followed by the function name and
parantheses ( ).
 Keyword def marks the start of function header.
 Function naming follows the same rules of writing identifiers in Python.
Step 2: Write the arguments inside the opening and closing parentheses of the function.
Parameters (arguments) through which we pass values to a function are optional.

Step 3: The code block within every function starts with a colon (:) and is indented.
Step 4: write the function body or program statements to be executed.
 The first statement of a function can be an optional statement - the documentation string
of the function that describes what the function does. It can be accessed with
function_name.__doc__ This statement is called Docstring.
 The indented line with one or more valid statements after the docstring makeup the body
of the function.
 Functions can have any number of lines,the end of a function is defined by the end of the
indentation.
Step 5: End the function with/without return statement(optional).
 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.
 The expression following the word return will be the output of the function. Functions
can only return once, so as soon as the return statement is executed the function stops.
Hence, return statements are usually the last line of a function..

VLITS II YEAR STUDENTS &STAFF


PYTHON 103

Syntax:

Let us see an example:

The above code can be written using parameters.

Significance of indentation in functions


Python functions don't have any explicit begin or end like curly braces to indicate the
start and stop for the function, so they have to rely on this indentation. At least, one indent is
enough to make your code work successfully. But as a best practice it is advisable to leave about
3-4 indent to call your function.Let us see the following example.

VLITS II YEAR STUDENTS &STAFF


PYTHON 104

It is also necessary that while declaring indentation, you have to maintain the same indent for the
rest of your code. unindent does not match any other indentation level.let us see the following
example:

Calling functions
How do you call functions in Python?
A function can be called by appending the arguments in parentheses to the function
name, or an empty matched set of parentheses if the function takes no arguments.Once we have
defined a function, we can call it from another function, program or even the Python prompt.
To call a function we simply type the function‘s name followed by ( ), placing any
required arguments within the brackets.we can call function in 2 ways.

With arguments
Syntax:

Look at the below example for calling a function with arguments.

VLITS II YEAR STUDENTS &STAFF


PYTHON 105

Without arguments
Syntax:

Let us see the following example:

Passing arguments
Argument
An argument in context with functions is the actual value that is passed to the function (
as input) ,when it is called. However parameter refers to the variables that are used in the
function declaration/definition to represent those arguments that were send to the function
during the function call.

The most common evaluation strategy when passing arguments to a function has been
call by value and call by reference.

Call by value
The most common strategy is the call-by-value evaluation, sometimes also called pass-
by-value. This strategy is used in C and C++.

In call-by-value, the argument expression is evaluated, and the result of this evaluation is
bound to the corresponding variable in the function.

VLITS II YEAR STUDENTS &STAFF


PYTHON 106

So, if the expression is a variable, a local copy of its value will be used, i.e. the variable
in the caller's scope will be unchanged when the function returns.

Call by reference
In call-by-reference evaluation, which is also known as pass-by-reference, a function gets
an implicit reference to the argument, rather than a copy of its value.

As a consequence, the function can modify the argument, i.e. the value of the variable in the
caller's scope can be changed.

 So,special care has to be taken to "protect" the values, which shouldn't be changed.
 Many programming language support call-by-reference, like C or C++, but Perl uses it as
default.

Correctly speaking, Python uses a mechanism, which is known as "Call-by-Object",


sometimes also called "Call by Object Reference" or "Call by Sharing" i.e arguments are
passed by assignment.

If you pass immutable arguments like integers, strings or tuples to a function, the passing
acts like call-by-value. The object reference is passed to the function parameters. They can't be
changed within the function, because they are immutable.

It's different, if we pass mutable arguments. They are also passed by object reference, but
they can be changed in place in the function.

Passing arguments can be done in different ways:

 Arguments are declared in the function definition. While calling the function, you can
pass the values for that args as shown below.

 We can declare default value of an argument,by just assigning a value at function


definition.
 We can also change the order of arguments that can be passed in python.
 Multiple arguments can also be passed.
 Unlike other languages,function overloading is not supported by python.

Passing arguments can be clearly understood by the following types of function arguments.
In python,arguments are passed by assignment.

VLITS II YEAR STUDENTS &STAFF


PYTHON 107

Types of arguments
You can call a function by using the following types of formal arguments:
 Required arguments
 Default arguments
 Keyword arguments
 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.
Let us see the following example:

Let‘s see what happens if we do not give required no.of parameters.

VLITS II YEAR STUDENTS &STAFF


PYTHON 108

If we pass more arguments in function call which are not mentioned in function definition,then
also it shows an error.Let us see the following example.

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.If we want to pass
actual parameters in different order to function definition i.e same name or keyword should be
used in formal parameters.
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.Let us see the following
example:

As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments.
Having a positional argument after keyword arguments will result into errors. For example the
function call as follows:

VLITS II YEAR STUDENTS &STAFF


PYTHON 109

One more case in keyword arguments is giving multiple values to same keyword. Let us see the
following example:

In the above example,observe second call to the show( ) function.Here 1st argument is 90,then
the interpreter assigns 90 to the name which is 1st argument in function definition.so when we
have assign name=‘john‘ second time its shows an error that is argument name got multiple
values.

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.

In the above example observe second call of printinfo( ) function.we did not provide ‗age‘ as an
argument.But in formal parameters we are having an argument as ‗age‘.So the function call takes
age=35 as default argument.
 One more important point in default arguments is in function definition ―non default
arguments follows default arguments‖otherwise it shows an error.

VLITS II YEAR STUDENTS &STAFF


PYTHON 110

Let us see the following example:

Let us see one more example regarding default arguments.

In the above example second call to show( ) assigns 90 to name since interpreter assigns its 1 st
argument in actual parameters to 1st argument formal parameters ….nth argument in actual
parameters to nth argument in formal parameters.

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.These are also called as arbitrary
arguments.
Syntax

def function_name(formal_args,*var_args_tuple):
―function doc string‖
functiom_suite
return[expression]

VLITS II YEAR STUDENTS &STAFF


PYTHON 111

An asterisk (*) is placed before the variable name that holds the values of all non keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call. To understand variable-length arguments we must know about args and kwargs.

In the function header, a simple name is matched by position or name (depending on how the
caller passes it), but the name=value form specifies a default value, the *name collects any extra
positional arguments in a tuple, and the **name form collects extra keyword arguments in a
dictionary.
*args and *kwargs:
*args and **kwargs are mostly used in function definitions. The special syntax,*args and
**kwargs allow you to pass a variable number of arguments to a function. What does variable
mean here is that you do not know before hand that how many arguments can be passed to your
function by the user so in this case you use these two keywords.
.The single asterisk form (*args) is used to pass a non-keyworded, variable-length argument list,
and the double asterisk form is used to pass a keyworded, variable-length argument list.You
should use **kwargs if you want to handle named arguments in a function.
 It is not necessary to write *args or **kwargs. Only the * (aesteric) is necessary. You
could have also written *var and **vars. Writing *args and **kwargs is just a
convention.
Order of using *args,**kwargs anf formal arguments:So if we want to use all of these three
then the order is:
def fun_name(fargs,*args,**kwargs)
If you choose to use and combine the special matching modes, Python has two ordering rules:
 In the function call, keyword arguments must appear after all non- keyword arguments.
 In a function header, the *name must be after normal arguments and defaults,
and **name must be last.
Moreover, Python internally carries out the following steps to match arguments before
assignment:
1. Assign non keyword arguments by position.
2. Assign keyword arguments by matching names.
3. Assign extra non keyword arguments to *name tuple.
4. Assign extra keyword arguments to **name dictionary.
5. Assign default values to unassigned arguments in header.

Let‘s see an example following the above rules:

VLITS II YEAR STUDENTS &STAFF


PYTHON 112

Lets see an example on usage of **kwargs:

Here, we have called the function with multiple arguments. These arguments get wrapped up into
a tuple before being passed into the function.We can also use ** symbol in arguments for more
points refer ―passing arguments‖ concept.

Anonymous functions
Python supports the creation of anonymous functions (i.e. functions that are not bound to
a name) at runtime.Anonymous function is a function that is defined without a name and
described by a single expression.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword. Hence, anonymous functions are also called lambda
functions.
The lambda operator or lambda function is a way to create small anonymous functions, i.e.
functions without a name. These functions are throw-away functions, i.e. they are just needed
where they have been created. Lambda functions are mainly used in combination with the
functions filter( ), map( ) and reduce( ). The lambda feature was added to Python due to the
demand from Lisp programmers.
A lambda function has the following syntax.
Syntax

lambda [arg1,[arg2,….,arg n]]: expression

VLITS II YEAR STUDENTS &STAFF


PYTHON 113

Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever function objects
are required.
The argument list consists of a comma separated list of arguments and the expression is an
arithmetic expression using these arguments. You can assign the function to a variable to give it
a name. The following example of a lambda function returns the sum of its two arguments:

This piece of code shows the difference between a normal function definition ("f") and a lambda
function ("g"):

As you can see, f( ) and g( ) do exactly the same and can be used in the same ways. Note that the
lambda definition does not include a "return" statement -- it always contains an expression which
is returned. Also note that you can put a lambda definition anywhere a function is expected, and
you don't have to assign it to a variable at all.
You can use a lambda function without even assigning it to a variable.This may not be the most
useful thing in the world,but it just goes to show that a lambda is just an in-line function.
So code complexity is reduced by using lambda functions:

Key points
 Lambda functions has no name.
 Lambda functions can take any number of arguments.
 Lambda functions does not have an explicit return statement.But it always contain an
expression which is return.
 Lambda functions cannot even access global variables.
 We can pass lambda functions as arguments to other functions.
 We can have lambda function and general function both in the same program.
 Anonymous function cannot be a direct call to print because it lambda requires an
expression.
 They are a 1 line version of a function and hence cannot contain commands or multiple
expressions.
 Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list.

VLITS II YEAR STUDENTS &STAFF


PYTHON 114

Don't try to squeeze too much into a lambda function; if you need something more complex,
define a normal function instead and make it as long as you want. Lambda functions are a
matter of style. Using them is never required; anywhere you could use them, you could define a
separate normal function and use that instead.

Use of Lambda Function


We use lambda functions when we require a nameless function for a short period of
time.In Python, we generally use it as an argument to a higher-order function (a function that
takes in other functions as arguments).
Lambda functions are mainly used in combination with the functions filter( ), map( ) and
reduce( ).All of the three functions expect two arguments: A function and a list.

map( ) function
The advantage of the lambda operator can be seen when it is used in combination with the map( )
function .map( ) is a function with two arguments,it takes in a function and a list.
Syntax
r=map(func,iterable, )
 function - map( ) passes each item of the iterable to this function.
 iterable- iterable which is to be mapped.

The first argument func is the name of a function and the second a sequence (e.g. a list) seq.You
can pass more than one iterable to the map() function.

Return Value from map( )


The map( ) function applies a given to function to each item of an iterable and returns a list of the
results. Using map is equivalent to for loops
Most of the times we want to pass all the list elements to a function one-by-one and then collect
the output.The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each item.
Here is an example use of map() function to double all the items in a list.

Instead of a list of inputs we can even have a list of functions.

VLITS II YEAR STUDENTS &STAFF


PYTHON 115

Since it's a built-in, map is always available and always works the same way. It also has some
performance benefit because it is usually faster than a manually coded for loop. On top of
those, map can be used in more advance way.

Use with filter( )


As the name suggests filter extracts each element in the sequence for which the function
returns True. The filter() function in Python takes in a function and a list as arguments.
The filter filters out items based on a test function which is a filter and apply functions to pairs
of item .
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e.
either True or False. This function will be applied to every element of the list l. Only if f returns
True will the element of the list be included in the result list.

Return value from filter( )


The function is called with all the items in the list and a new list is returned which
contains items for which the function evaluates to True.
If function is None, return the items that are true. If sequence is a tuple or string, return the
same type, else return a list.
Here is an example use of filter() function to filter out only even numbers from a list.

Fruitful functions
Functions which return some values are called as fruitful functions.Before going to learn about
fruitful functions ,let‘s have a look on return statement.

VLITS II YEAR STUDENTS &STAFF


PYTHON 116

The return statement


The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function, then
the function will return the None object.
The first example is area, which returns the area of a circle with the given radius:

We have seen the return statement before, but in a fruitful function the return statement includes
an expression. This statement means: ―Return immediately from this function and use the
following expression as a return value.‖ The expression can be arbitrarily complicated, so we
could have written this function more concisely:

On the other hand, temporary variables like temp often make debugging easier.Let us go deep
into this.
 Sometimes it is useful to have multiple return statements, one in each branch of a
conditional.

Since these return statements are in an alternative conditional, only one will be executed.

VLITS II YEAR STUDENTS &STAFF


PYTHON 117

As soon as a return statement executes, the function terminates without executing any subsequent
statements.
 Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.
 In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement.
For example:

This function is incorrect because if x happens to be 0 , neither condition is true, and the function
ends without hitting a return statement. If the flow of execution gets to the end of a function, the
return value is None, which is not the absolute value of 0.
 We can return multiple values using only one return statement.let us see an example.

 We can reduce our lines of code using return function.Let us see an example.

This example can be reduced as follows:

VLITS II YEAR STUDENTS &STAFF


PYTHON 118

Recursive Functions
Recursion is a way of programming or coding a problem, in which a function calls itself
one or more times in its body. Usually, it is returning the return value of this function call. If a
function definition fulfils the condition of recursion, we call this function a recursive function.

Termination condition
A recursive function has to terminate to be used in a program. A recursive function
terminates, if with every recursive call the solution of the problem is downsized and moves
towards a base case. A base case is a case, where the problem can be solved without further
recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls.
Generally we can say: Recursion in computer science is a method where the solution to a
problem is based on solving smaller instances of the same problem.

Recursive functions in python


Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

 In the above example, calc_factorial( ) is a recursive functions as it calls itself.


 When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
 Each function call multiples the number with the factorial of number 1 until the number
is equal to one. This recursive call can be explained in the following steps.

calc_factorial(4) # 1st call with 4


4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th call as number=1
4*3*2 # return from 3rd call
4*6 # return from 2nd call

VLITS II YEAR STUDENTS &STAFF


PYTHON 119

24 # return from 1st call


Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.

Printing fibanocci series using recursion:

Let's have a look at the calculation tree, i.e. the order in which the functions are called. fib() is
substituted by fib( ).

We can see that the subtree f(2) appears 3 times and the subtree for the calculation of f(3) two
times. If you imagine extending this tree for f(6), you will understand that f(4) will be called two

VLITS II YEAR STUDENTS &STAFF


PYTHON 120

times, f(3) three times and so on. This means, our recursion doesn't remember previously
calculated values.
Advantages of recursion
 Recursive functions make the code look clean and elegant.
 A complex task can be broken down into simpler sub-problems using recursion.
 Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of recursion:
 Sometimes the logic behind recursion is hard to follow through.
 Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
 Recursive functions are hard to debug.

Scope of variables in functions

Local and global variables


All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable .The scope of a variable determines the portion
of the program where you can access a particular identifier. There are two basic scopes of
variables in Python −
 Global variables
 Local variables
Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.

This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
In Python when you want to use the same variable for rest of your program or module you
declare it global variable, while if you want to use the variable in a specific function or method
you use local variable. If a variable with same name is defined inside the scope of function as
well then it will print the value given inside the function only and not the global value.
Let's have a look at the following function:

The variable s is defined as the string "‘I love python", before we call the function f( ).
The only statement in f( ) is the "print (s)" statement. As there is no local s, the value from the
global s will be used. So the output will be the string "I love python".
The question is, what will happen, if we change the value of s inside of the function f( )?
Will it affect the global s as well? We test it in the following piece of code:

VLITS II YEAR STUDENTS &STAFF


PYTHON 121

What if we combine the first example with the second one, i.e. first access s and then assigning a
value to it?
It will throw an error, as we can see in the following example:

If we execute the previous script, we get the error message:

Python "assumes" that we want a local variable due to the assignment to s inside of f( ),
so the first print statement throws this error message. Any variable which is changed or created
inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we
want to use the global variable, we have to use the keyword "global".
Let's understand this difference between local and global variable with the below program.
Here is an example in which local and global variables are declared.

Now,let‘s see the above program by using keyword global. Using the keyword global, you can
reference the a global variable inside a function

VLITS II YEAR STUDENTS &STAFF


PYTHON 122

In the above program,we declared f as global in local scope thus f is updated to ―I am learning
python‖ and thus the result.
Now let‘s see another example declaring variable as global in local scope.

In the above program, f is declared as global variable as well as local variable and f is updated to
―python‖.

Scope and Life time of variables

A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists
only in block 3.This is called as scope of a variable.

VLITS II YEAR STUDENTS &STAFF


PYTHON 123

Scope: A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed. The scope of the local variable
is within the function or block in which it was declared.
Lifetime: A local variable remains in memory until the execution of the function or block in
which it was declared in completes.Even the control of interpreter changes it‘s direction and
comes back to it‘s point the value of a variable is not dead.This is called Lifetime of a variable.
Consider below program to understand lifetime of a variable.

Observe n, the interpreter changes it‘s direction from line 7 to line 3 to execute x( ) block and
returns back to line 8 and continues interpreting code. Even the control changes it‘s direction it
does not effect the value of n because of it‘s global nature.
Type of variable Declaration location Scope(visibility) Lifetime
Local variable Inside a function block. Within the function From the point of its
block only. definition to the end
of the function block
in which it is defined.
Global variable They are defined in the Can be accessed Until the program
body of the main program/ through out the terminates.
Outside a function block. program file even
inside a function
block also.

Modules
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended.

Creating modules
A file containing Python code, for e.g. sample.py, is called a module and its module name would
be sample.

VLITS II YEAR STUDENTS &STAFF


PYTHON 124

 We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
 We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Let us create a module. Type the following and save it as example.py.

Here, we have defined a function add( )inside a module named example. The function takes in
two numbers and returns their sum.
Modules are of two types:

1. Predefined modules
2. user-defined modules
Predefined modules
There are various predefined modules in python. Among them the various types frequently used
modules are given as:
 Predefined modules are the built-in modules developed by the programmers and are
updated in the python library.
 We can‘t i.e., users can not access the predefined modules directly to work out.
 In order to work with the modules or wanted to access it we use import statement or from
import or from import *.
Let us see a few examples on accessing predefined modules using import statements.

Example: program to explain the usage of import statement

Example: program to explain the usage of from import statement

VLITS II YEAR STUDENTS &STAFF


PYTHON 125

Special case Example: program using command line arguments

User defined modules


Apart from the usage of predefined modules we can also create modules. As the python is an
open source we can create and upload it on the internet directly. So that anyone can access it by
their necessity of program requirement.

Name of module: Every module has a name. You can find the name of module by using the
_name_ attribute of module.

Making our own modules: You can easily create as many modules as you want.In fact, you
have already been doing that.Every python program is a module, that is every file that you save
as .py extension is a module.

 Here in the below example we are just accessing variables and functions from one
program file to another program file without creating specific memory for them
separately with the help of import statement.
 The basic condition to work out with this type of accessing is that the both the files must
be in of same folder or same directory otherwise an error generates.consider the
following example

VLITS II YEAR STUDENTS &STAFF


PYTHON 126

Module Loading and Execution


 A module imported in a program must be located and loaded into memory before it can
be used.
 Python first searches for the module in the current working directory. If the module is not
found there, it then looks for the module in the directories specified in the
PYTHONPATH environment variable.
 If the module is still not found or if the PYTHONPATH variable is not defined ,then a
python installation-specific path(like c:\python34\lib) is searched. If the module is not
located even there, then an error IMPORT ERROR exception is generated.
 Till now, we have saved our modules in the same directory as that of the program
importing it. But, if you want the module to be available to the other programs as well,
then the module should be either saved in the directory specified in the PYTHONPATH ,
or stored in the python installation Lib directory.

Once a module is located , it is loaded in memory . A new compiled version of the module with
file extension.pyc is generated. Next time when the module is imported, thi.pycfile is loaded,
rather than the .pyfile, to save the time of recompiling. A new compiled version of a module is
again produced whenever the compiled version is out of date(based on the dates when the.pyc
file was created/modified). Even the progrmmer can force the python shell to reload and
recompile the .py file to generate the new .pyc file by using the reload( ) function.

Module search path


When a module named spam is imported, the interpreter first searches for a built-in module with
that name. If not found, it then searches for a file named spam.py in a list of directories given by
the variable sys.path. sys.path is initialized from these locations:
 The directory containing the input script (or the current directory).
 PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
 The installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the script
being run is placed at the beginning of the search path, ahead of the standard library path. This
means that scripts in that directory will be loaded instead of modules of the same name in the
library directory. This is an error unless the replacement is intended.

Program to print the sys.path variable

VLITS II YEAR STUDENTS &STAFF


PYTHON 127

Reloading a module
The Python interpreter imports a module only once during a session. This makes things
more efficient. Here is an example to show how this works.Suppose we have the following code
in a module named my_module.

Now we see the effect of multiple imports.

We can see that our code got executed only once. This goes to say that our module was imported
only once.
Now if our module changed during the course of the program, we would have to reload it. One
way to do this is to restart the interpreter. But this does not help much.
Python provides a neat way of doing this. We can use the reload() function inside the imp
module to reload a module. This is how its done.

import statement
You can use any Python source file as a module by executing an import statement in
some other Python source file. The import has the following syntax:

Python modules

VLITS II YEAR STUDENTS &STAFF


PYTHON 128

When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches before
importing a module. For example, to import the module support.py, you need to put the
following command at the top of the script –

When the above code is generated it produces the following the result:

A module is loaded only once, regardless of the number of times it is imported. This prevents
the module execution from happening over and over again if multiple imports occur.

The from……import statement


Python's from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax –

For example, to import the function fibonacci from the module fib, use the following
statement –

This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the importing
module.

The from….import * statement


It is also possible to import all names from a module into the current namespace by using
the following import statement –

This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

VLITS II YEAR STUDENTS &STAFF


PYTHON 129

Name spacing
Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).
Namespace is of three types:
1.Global namespace
2. Local namespace
3.Built-in namespace

 A Python statement can access variables in a local namespace and in the global
namespace.
 If a local and a global variable have the same name, the local variable shadows the global
variable.
 Each function has its own local namespace. Class methods follow the same scoping rule
as ordinary functions.
 Python makes educated guesses on whether variables are local or global. It assumes that
any variable assigned a value in a function is local.
 Therefore, in order to assign a value to a global variable within a function, you must first
use the global statement.
 The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the function Money,
we assign Money a value, therefore Python assumes Money as a local variable.
However, we accessed the value of the local variable .
Money before setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.

 Here the built-in namespace as the name suggests that it consists of all built-in functions,
constants, variables etc..,

VLITS II YEAR STUDENTS &STAFF


PYTHON 130

The dir ( ) function:


The dir( ) tries to return a list of valid attributes of the object.
 If the object has __dir__( ) method, the method will be called and must return the list of
attributes.
 If the object doesn't have __dir( )__ method, this method tries to find information from
the __dict__ attribute (if defined), and from type object. In this case, the list returned
from dir( ) may not be complete.
If object is not passed to the dir( ) method, it returns the list of names in the current local scope.

The syntax of dir( ) is:


dir([object])

dir ( )Parameters
The dir( ) takes maximum of one object.
 object (optional) - dir( ) attempts to return all attributes of this object.

Example: program to demonstrate the usage of dir( ) function:

Python Packages
Introduction to PIP
 We don't usually store all of our files in our computer in the same location. We use a
well-organized hierarchy of directories for easier access.
 Similar files are kept in the same directory, for example, we may keep all the songs in the
"music" directory. Analogous to this, Python has packages for directories and
modules for files.
 As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a
project (program) easy to manage and conceptually clear.
 Similar, as a directory can contain sub-directories and files, a Python package can have
sub-packages and modules.
 Here is an example. Suppose we are developing a game, one possible organization of
packages and modules could be as shown in the figure below.

VLITS II YEAR STUDENTS &STAFF


PYTHON 131

Installing packages via PIP


 Pip is a tool for installing python packages from the python package index.
 Python‖ virtual environments‖ allow python to be installed in an isolated location for a
particular application, rather than being installed globally.
 In python, many third-parties are stored in python package index (PyPI).
 To install them, you can use a program called ‗pip‘.
 However, new versions of python have these modules installed by default.
 Once you have these modules, installing libraries from PyPI becomes very easy.
 Simply, goto the command line (for windows it will be the command prompt), enter the
following code.

 Once the library is installed, input it in your program and use it in your code.
 Using pip is the standard way of installing libraries on most operating systems, but some
libraries have re-built binaries (executable files) for windows which can be installed with
a GUI(Graphical User Interface) the same way you would install other programs.
 To install the latest version of “some project”

 To install a specific version

 To install greater than or equal to one version and less than another.
pip install 'someproject>=1,<2'

VLITS II YEAR STUDENTS &STAFF


PYTHON 132

Installing to the user site:


 To install packages that are isolated to the current user, use the “__user” flag.

Upgrading packages
 Upgrade an already installed someproject to the latest from PyPI.

Using python packages


 A package is a hierarchical file directory structure that has modules and other packages
with in it.
 Like modules, you can very easily create packages in python
 Remember that, every package in python is a directory which must have a special file
called __init__.py. This file may not even have a single line of code.
 It is simply added to indicate that this directory is not an ordinary directory and contains a
python package.
 In your programs, you can import a package in the same way as you import any module.
 For example, to create a package called MyPackage, create a dictionary called
MyPackage having the module MyModule and the __init__.py file.
Now, to use MyModule in a program, you must first import it. This can be done in two ways as
shown below:

The import statement first checks if the item is defined in the package. If it is unable to find it ,
an ImportError exception is raised.
Suppose,for example, that we had a fictitious set of module files for reading and writing various
graphics file formats , such as Bmp.py , Jpeg.py , Png.py , Tiff.py, and Xpm.py , all of which
provided the functions load( ), save( ), and so on .
 We could keep the modules in the same directory as our program , but for a large
program that uses scores of custom modules the graphics modules will be dispersed .
 By putting them in their own subdirectory , say, graphics they can be kept together . And
if we put an empty __init__.py file in the graphics directory along with them , the
directory will become a package shown below.

 As long as the graphics directory is a subdirectory inside our program‘s directory or is in


the python path, we can import any of these modules and make use of them .

VLITS II YEAR STUDENTS &STAFF


PYTHON 133

 We must be careful to ensure that our top-level module name is not the same as any top-
level name in the standard library so as to avoid name conflicts .
Here‘s how we can import and use our module :

 For short programs some programmers prefer to use shorter names and python makes this
possible using two slightly different approaches.

Here we have imported the Jpeg module from the graphics package and told python that we want
to refer to it simply as Jpeg rather than using its fully qualified name, Graphics. Jpeg.
 So far we have shown only one level of nesting , but python allows us to nest packages as
deeply as we like.
 So we could have a subdirectory inside the graphics directory , say , Vector , with module
files inside that , such as Eps.py and Svg.py as shown below.

For the Vector directory to be a package it must have an __init__.py file, and as noted , this can
be empty or could have an __all__ list as a convenience for programmers who want to import
using from Graphics.Vector import * .
 To access a nested package we just build on the syntax we have already used.

VLITS II YEAR STUDENTS &STAFF


PYTHON 134

Object oriented programming (oop) in Python


 Classes
 Self variable
 Methods
 Constructor method
 Inheritance
 Overriding methods
 Data hiding

Error and Exceptions


 Difference betwwen an error and exception
 Handling exception
 Try except block
 Raising exceptions
 User defined exceptions

VLITS II YEAR STUDENTS &STAFF


PYTHON 135

5.OOP IN PYTHON
Python has been an object-oriented language since the time it existed. Due to this,
creating and using classes and objects are downright easy. This chapter helps you become an
expert in using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you may
want to consult an introductory course on it or at least a tutorial of some sort so that you have a
grasp of the basic concepts.
However, here is a small introduction of Object-Oriented Programming (OOP) to help you −

Overview of OOP Terminology

Class − A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.

Class variable − A variable that is shared by all instances of a class. Class variables are defined
within a class but outside any of the class's methods. Class variables are not used as frequently as
instance variables are.

Data member − A class variable or instance variable that holds data associated with a class and
its objects.

Function overloading − The assignment of more than one behaviour to a particular function.
The operation performed varies by the types of objects or arguments involved.

Instance variable − A variable that is defined inside a method and belongs only to the current
instance of a class.

Inheritance − The transfer of the characteristics of a class to other classes that are derived from
it.

Instance − An individual object of a certain class. An object obj that belongs to a class Circle,
for example, is an instance of the class Circle.

Instantiation − The creation of an instance of a class.

Method − A special kind of function that is defined in a class definition.

Object − A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods.

Operator overloading − The assignment of more than one function to a particular operator.

Key points on OOP in python

 Classes and objects are introduced to use the memory in efficient way.
 Class is a collection of different datatypes.
 In ‗C‘ structure is a collection of different datatypes.

VLITS II YEAR STUDENTS &STAFF


PYTHON 136

 Similar concepts exists in JAVA (object oriented programming language) as classes and
objects.
 Python is mainly designed with OOP concepts.A class can contain different datatype
elements and methods.

Python classes and objects


 Classes and objects introduce the nature of dynamic programming.
 Classes and objects are the two main aspects of object oriented programming.
 In python everything is an object or instance of the class.
 Python standard library is based on the concept of classes and objects.
 Every class is having its own namespace.

Classes
Classes provide a means of bundling data and functionality together. Creating a new class
creates a new type of object, allowing new instances of that type to be made. Each class instance
can have attributes attached to it for maintaining its state. Class instances can also have methods
(defined by its class) for modifying its state.
Python classes provide all the standard features of Object Oriented Programming: the class
inheritance mechanism allows multiple base classes, a derived class can override any methods of
its base class or classes, and a method can call the method of a base class with the same name.
Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake
of the dynamic nature of Python: they are created at runtime, and can be modified further after
creation.

Class objects

Defining a Class in Python


Like function definitions begin with the keyword def, in Python, we define a class using
the keyword class followed by the class name and colon(:).
The first string is called docstring and has a brief description about the class. Although not
mandatory, this is recommended.

class ClassName:
'Optional class documentation string'
class_suite
 The class has a documentation string, which can be accessed via ClassName.__doc__.
 The class_suite consists of all the component statements defining class members, data
attributes and functions.

VLITS II YEAR STUDENTS &STAFF


PYTHON 137

 The statements in this class_suite definition be any of these sequential


instructions,decisions control statements,loop statements,and we can include function
defnitions.

Here is a simple class definition

class MyNewClass:
'''This is a docstring. I have created a new class'''
pass

A class creates a new local namespace where all its attributes are defined. Attributes may be data
or functions.
There are also special attributes __init__ that begins with double underscores (__).The variables
in classes are also called as attributes. For example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This class object
allows us to access the different attributes as well as to instantiate new objects of that class.Let us
see the following example:

class

Creating objects
Once aclass is defined ,the next job is to create an object (or instance ) of that class.The
object can then access class variables and class methods using the dot operator (.) .
syntax to create an object:
object_name=class_name( )

VLITS II YEAR STUDENTS &STAFF


PYTHON 138

Creating an object or instance of a class is know as instantiation .From the syntax ,we can see
that class instantiation uses function notation .
Object_name.class_member_name

Example program to access the class variables using class objects:

In the above example ,we defined a class ABC which has a variable var having a value 10.Object
of the class is created and used to access the class variable using the dot operator. Thus ,we can
think of a class has a factory for making objects.

Let us see an another example:

Class methods and self -variables


Method:
A method is a function specific to a class, accessed using an instance/object of the
class.Method is just a function object created by def statement inside a class.Method works in
exactly the same way as a simple function. But there is one exception: a method's first argument
always receives the instance object.
The only difference between method and a function is that, methods are associated with
object instances or classes; functions aren't. When Python calls a method, then it binds the first
parameter of that call to the appropriate object reference. (For most methods that's
conventionally called self).
To understand briefly regarding objects,class method ans self variables, let‘s see an
another example.In this example we can see how objects can access the data members and
member functions in the class.

VLITS II YEAR STUDENTS &STAFF


PYTHON 139

The following example makes you understand what is a method.

You may have noticed the self parameter in function definition inside the class but, we
called the method simply as ob.func( ) without any arguments. It still worked.
This is because, whenever an object calls its method, the object itself is passed as the first
argument. So, ob.func( ) translates into myClass.func(ob).
In general, calling a method with a list of ‗n‘ arguments is equivalent to calling the
corresponding function with an argument list that is created by inserting the method's object
before the first argument.
For these reasons, the first argument of the function in class must be the object itself. This is
conventionally called self. It can be named otherwise ,but we highly recommend to follow the
convention.
Now you must be familiar with class object, instance object, function object, method object and
their differences.
Class objects support two kinds of operations: attribute references and instantiation.Let‘s begin
by writing a (Python 3) class that contains simple examples for all three method types:

 Instance methods need a class instance and can access the instance through self.
 Class methods don‘t need a class instance. They can‘t access the instance (self) but they
have access to the class itself via cls.
 Static methods don‘t have access to cls or self. They work like regular functions
Simple method
It is defined outside of a class. This function can access class attributes by feeding
instance arg.
Instance method
A Method which first argument will be instance object(self)

VLITS II YEAR STUDENTS &STAFF


PYTHON 140

In instance method the inner working of instance method is the same as the class method.
Actually, Python automatically maps an instance method call to a class method. For instance, a
call like this:

will be automatically converted to a class method function call like this:

Example:

Class method
Class Method is to work on class specific data, A method written inside class body which
pass class object as its first argument.We prefer class method if we need to use class attributes.
Static method
Static Method is for Class object and all instance objects, A simple method written inside
class body which doesn‘t pass any extra object(instance or class) automatically.This method do
not have any info about class.
Example

VLITS II YEAR STUDENTS &STAFF


PYTHON 141

Self variables
 Class methods(functions defined in the class) are exactly same as ordinary functions that
we have been defining so far with just one small difference.
 Class methods must have first argument named as self.
 This is the first argument that is added to the beginning of the parameter list.
 Moreover,we do not pass a value for this parameter when you call the method.
 Python provides the value automatically..
 The self argument refers to the object iself,i.e the object that has called the method.
 This means that even if a method that takes no arguments should be defined to accept the
argument self.
 Since,the class methods uses self,they require an object or instance of the class to be
used,for this reason they are often referred to as instnace methods.

In this session we are going to know- how to do object instantiation, how to create instance
attributes in Python.
Once there are attributes that belong to the class, you can define functions that will access the
class attribute. These functions are called methods. When you define methods, you will need to
always provide the first argument to the method with a ‗self‟ keyword.
For example, you can define a class Snake, which has one attribute name and one
method change _name. The method change name will take in an argument new_name along
with the keyword self.

VLITS II YEAR STUDENTS &STAFF


PYTHON 142

Now, you can instantiate this class Snake with a variable snake and then change the name with
the method change_name.

Constructor method
Class functions that begins with double underscore (__) are called Constructors.They are
also called as special functions as they have special meaning.
 The __init__( ) special function gets called whenever a new object of that class is
instantiated.
 This type of function is also called constructors in Object Oriented Programming (OOP).
We normally use it to initialize all the variables.
 The init method has a special significance in python classes. This method is automatically
executed when an object of a class is created.
 This function is prefixed and suffixed by(__) double underscore.

Example:

Keypoints
 Whenever object is created the class is called.When you pass a value whenever object is
created that value is an input to constructor.
 Constructor is called whenever object is created.it cannot be assigned directly but by
using self.var=val.

VLITS II YEAR STUDENTS &STAFF


PYTHON 143

 In c++ and java constructor name should be same as class name,but in python it is
__init__.

Instance attributes in python and the init method


You can also provide the values for the attributes at runtime. This is done by defining the
attributes inside the init method. The following example illustrates this.

Now you can directly define separate attribute values for separate objects. For example,

Example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 144

Inheritance
Every object-oriented programming language would not be worthy to look at or use, if it weren't
to support inheritance. Of course, Python supports inheritance, it even supports multiple
inheritance. A few points regarding inheritance are:
 Classes can inherit from other classes.
 A class can inherit attributes and behaviour methods from another class, called the
superclass or baseclass.
 A class which inherits from a superclass is called a subclass, also called heir class or
child class. Superclasses are sometimes called ancestors as well.
 There exists a hierarchy relationship between classes.
It's similar to relationships or categorizations that we know from real life.

Image representation of inheritance

VLITS II YEAR STUDENTS &STAFF


PYTHON 145

Let us see the an example regarding vehicles.

Bikes, cars, buses and trucks are vehicles. pick-ups, vans, sports cars, convertibles and estate cars
are all cars and by being cars they are vehicles as well. We could implement a vehicle class in
Python, which might have methods like accelerate and brake. Cars, Buses and Trucks and Bikes
can be implemented as subclasses which will inherit these methods from vehicle.
Syntax of inheritance

Derived class inherits features from the base class, adding new features to it. This results into re-
usability of code.Let us see the following example for better understanding of inheritance.

VLITS II YEAR STUDENTS &STAFF


PYTHON 146

Basically there are three types of inheritance in python.They are:

Single inheritance
The process of deriving only one class from a parent class is called as single inheritance.

Single inheritance

Let us see the following example:

Animal is the parent or base class and Dog is the child class.Here, we are defining eat() method
in Animal class and bark( ) method in Dog class. In this example, we are creating instance of
Dog class and calling eat( ) and bark( ) methods by the instance of child class only. Since, parent
properties and behaviors are inherited to child object automatically, we can call parent and child
class methods by the child instance only.

Multiple inheritance
When a class is derived from more than base class then it is called as multiple inheritance.In
multiple inheritance, the features of all the base classes are inherited into the derived class. The
syntax for multiple inheritance is similar to single inheritance.

VLITS II YEAR STUDENTS &STAFF


PYTHON 147

Syntax:

Here, MultiDerived is derived from classes Base1 and Base2.

The class multiDerived inherits from both Base1 and Base2.


Following is an example of multiple inheritance.For better understandability of the example lets
see the following points:
 Person is the base class1
 Student is the base class2
 Resident is derived from these two classes which consists of methods of both the base
classes.
 In resident class first we have inherited the constructors of both the base classes by using
dot operator
 After that we have created an object for resident class ,which is used to access the
methods of both the base classes.Whenever we have created an object it automatically
initializes the constructor.

VLITS II YEAR STUDENTS &STAFF


PYTHON 148

Multilevel inheritance
In multilevel inheritance, features of the base class and the derived class is inherited into the new
derived class.

VLITS II YEAR STUDENTS &STAFF


PYTHON 149

Syntax:

Here, Derived1 is derived from Base, and Derived2 is derived from Derived1.

Let us see the following example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 150

We also have hybrid and heirarchal level of inheritances,but we will not use more.

Hybrid inheritance
The combination of one or more types of inheritances is called hybrid inheritance.

Hierarchial inheritance
The process of deriving more derived classes from single base class is called hierarchial
inheritance.

VLITS II YEAR STUDENTS &STAFF


PYTHON 151

Data hiding
In C++ and Java, things are pretty straight-forward. There are 3 magical and easy
to remember access modifiers, that will do the job (public, protected and private). But there‘s
such a thing even in Python. That might be a little confusing at first, but it‘s possible too.

Public
All member variables and methods are public by default in Python. So when you want to
make your member public, you just do nothing. See the example below:

The output will be as follows:

All of this is good and acceptable, because all the attributes and methods are public.

Protected
Protected member is (in C++ and Java) accessible only from within the class and it‘s
subclasses. How to accomplish this in Python? The answer is – by convention. By prefixing the
name of your member with a single underscore.
consider the following example:

The output will be as follows:

Same example as before, but the content of the cup is now protected. This changes virtually
nothing, you‘ll still be able to access the variable from outside the class.

VLITS II YEAR STUDENTS &STAFF


PYTHON 152

Private
By declaring your data member private you mean, that nobody should be able to access it
from outside the class. Python supports a technique called name mangling. This feature turns
every member name prefixed with at least two underscores and suffixed with at most one
underscore into _<className><memberName> . So how to make your member private? Let‘s
have a look at the example below:

The output is as follows:

Error and Exceptions


Error: occurs during compile time
Exception: occurs during run time

Difference between an error and exception


An Error "indicates serious problems that a reasonable application should not try to catch."
An Exception "indicates conditions that a reasonable application might want to catch." Error
along with runtime exception & their subclasses are unchecked exceptions.
Logical errors: This will not shows an error but gives us unexpected results.
Ex: writing an expression without following precedence
2+3*5 expected result: 25
Produced result: 17
 In some cases logical error may lead to divide by 0 or accessing an item in a list where
the index of the item is outside the bounce of a list.
 In these cases logical error leads to a runtime error that causes a program to terminate.
Syntax errors
Syntax errors occur during the parsing of input code, and are caused by
grammatically incorrect statements.

VLITS II YEAR STUDENTS &STAFF


PYTHON 153

 Placing semicolon after looping statements.


 Without placing semicolon after completion of statements.
 Without opening or closing the parenthesis of loops….etc.., are some of the reasons for
occurring syntax errors.
Synchronous exception
If the event occurs at the same place every time the program is executed with the same
data and memory allocation, the event is synchronous.
Ex: Tracing instruction execution
Invoke operating system
Integer arithematic overflow etc..,
Asynchronous exception
With the exception of hardware malfunctions, asynchronous events are caused by devices
external to the processor and memory.
Ex: I/O device request
Power failure
Hardware malfunction etc…,

VLITS II YEAR STUDENTS &STAFF


PYTHON 154

Handling exception
Python has many built-in exceptions which forces your program to output an error
when something in it goes wrong.
 When these exceptions occur, it causes the current process to stop and passes it to the
calling process until it is handled. If not handled, our program will crash.
 For example, if function A calls function B which in turn calls function C and an
exception occurs in function C. If it is not handled in C, the exception passes to B and
then to A.
 If never handled, an error message is spit out and our program come to a sudden,
unexpected halt.

In Python, exceptions can be handled using a try statement.


 A critical operation which can raise exception is placed inside the try clause and the code
that handles exception is written in except clause.
 It is up to us, what operations we perform once we have caught the exception.
 If no exception occurs, except block is skipped and normal flow continues. But if any
exception occurs, it is caught by the except block.
 This is not a good programming practice as it will catch all exceptions and handle every
case in the same way. We can specify which exceptions an except clause will catch.
 A try clause can have any number of except clause to handle them differently but only
one will be executed in case an exception occurs.
 We can use a tuple of values to specify multiple exceptions in an except clause.

try except block


To perform exception handling in python, you first need to have a catch all except clauses.
 The words "try‖ and ―except‖ are the python keywords which are used to catch the
exceptions.
 The code within the try clause will be executed statement by statement.
 If an exception occurs the rest of the try block statements gets skipped and the exception
clause gets executed.
 The exception handling is done through the use of exceptions that are caught in try block
and handled in except block.
 If an error is encountered a try block execution is stopped and transferred down to the
except block.
 In addition to the use of an exception block we can also use finally block.

VLITS II YEAR STUDENTS &STAFF


PYTHON 155

 The code in finally block is executed regardless whether an exception is occurred or not.

Syntax:

Ex:

From the above example we can say that, in case of division by zero we cannot write blindly
zero. Suppose if there is an exception like x/i then sometimes i is getting updated to zero
unknowingly. Then division by zero is not possible i.e., runtime exception.

Multiple exception blocks


Until then we have discussed about the exceptions that are raised individually
according to the particular type of code.
 Depending on the code we can have multiple exceptions too.
 So in order to eliminate those types of exceptions we are using the multiple exception
blocks.

VLITS II YEAR STUDENTS &STAFF


PYTHON 156

 In this multiple exceptions we have single try block statement with error condition and
multiple exception blocks.
 The error condition in the try block statement gets verified by each exception clause
statements depending on the input given by the user.
 And if any match found regarding the correct exception clause depending on the input,
the interpreter gets inside the exception block and the statements gets executed.
 Otherwise the remaining statements in the code gets executed and the program will
terminate.

Syntax:

Ex:

We can write the multiple exception statements in single line also

VLITS II YEAR STUDENTS &STAFF


PYTHON 157

While handling with different codes we will get different types of exceptions. The prominent
ones which we get raised commonly are as follows:

Raising 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.

VLITS II YEAR STUDENTS &STAFF


PYTHON 158

 In order to catch an exception, an "except" clause must refer to the same exception
thrown either as a class object or a simple string.

The following example illustrates the use of raising an exception.

This will produce the following result:

Re-raising Exceptions
We can also re-raise our exceptions in python.

Syntax:
try:
raise ExceptionName
except ExceptionName:
raise #re-raising exception

User Defined Exceptions


Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
 class for exceptions defined by that module, and subclass that to create specific exception
classes for different error conditions:
 Most exceptions are defined with names that end in ―Error,‖ similar to the naming of the
standard exceptions.
 Many standard modules define their own exceptions to report errors that may occur in
functions they define.

Consider the following example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 159

The output is as follows:

VLITS II YEAR STUDENTS &STAFF


PYTHON 160

Brief tour of the standard library


Operating system interfaces-
 String pattern matching
 Mathematics
 Internet access
 Dates and times
 Data compression
 Multithreading
 Gui programming
 Turtle graphics

Testing
 Why testing is required?
 Basi concepts of testing
 Unit testing in python
 Writing test cases
 Running tests

VLITS II YEAR STUDENTS &STAFF


PYTHON 161

6. BRIEF TOUR OF THE STANDARD LIBRARY


Operating system interface
Source code: Lib/os.py
This module provides a portable way of using operating system dependent functionality.
If you just want to read or write a file see open( ), if you want to manipulate paths, see the
os.path module, and if you want to read all the lines in all the files on the command line see the
fileinput module. For creating temporary files and directories see the tempfile module, and for
high-level file and directory handling see the shutil module.

Notes on the availability of these functions:


 The design of all built-in operating system dependent modules of Python is such that as
long as the same functionality is available, it uses the same interface; for example, the
function os.stat(path) returns stat information about path in the same format (which
happens to have originated with the POSIX interface).
 Extensions peculiar to a particular operating system are also available through the os
module, but using them is of course a threat to portability.
 All functions accepting path or file names accept both bytes and string objects, and result
in an object of the same type, if a path or file name is returned.

Note
All functions in this module raise OSError in the case of invalid or inaccessible file names and
paths, or other arguments that have the correct type, but are not accepted by the operating
system.

 os.name
The name of the operating system dependent module imported. The following names
have currently been registered: 'posix', 'nt', 'java'.

Process Parameters:
These functions and data items provide information and operate on the current process and user.

 os.ctermid( )

Return the filename corresponding to the controlling terminal of the process.

 os.environ
A mapping object representing the string environment. For example, environ[‗HOME‘] is
the pathname of your home directory (on some platforms), and is equivalent to
getenv(―HOME) in C.

This mapping is captured the first time the os module is imported, typically during Python
startup as part of processing site.py. Changes to the environment made after this time are not
reflected in os.environ, except for changes made by modifying os.environ directly.

VLITS II YEAR STUDENTS &STAFF


PYTHON 162

If the platform supports the putenv( ) function, this mapping may be used to modify the
environment as well as query the environment. putenv() will be called automatically when the
mapping is modified.
when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.
 os.environb
A mapping object representing the environment as byte strings. environ and environb are
synchronized (modify environb updates environ, and vice versa).

environb is only available if supports_bytes_environ is True.

 os.chdir(path), os.fchdir(fd), os.getcwd( )


These functions are described in Files and Directories.

 os.fsencode(filename)
Encode path-like filename to the filesystem encoding with 'surrogateescape' error handler,
or 'strict' on Windows; return bytes unchanged.

 os.fspath(path)
Return the file system representation of the path. If str or bytes is passed in, it is returned
unchanged. Otherwise __fspath__( ) is called and its value is returned as long as it is a str or
bytes object. In all other cases, TypeError is raised.

 class os.PathLike
An abstract base class for objects representing a file system path, e.g. pathlib.PurePath

 os.getenv(key, default=None)
Return the value of the environment variable key if it exists, or default if it doesn‘t. key,
default and the result are str.

 os.getenvb(key, default=None)
Return the value of the environment variable key if it exists, or default if it doesn‘t. key,
default and the result are bytes.getenvb( ) is only available if supports_bytes_environ is True.

 os.fspath(path)
Return the file system representation of the path.

If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__( ) is called and its
value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised.

 class os.PathLike
An abstract base class for objects representing a file system path.

 os.getlogin( )
Return the name of the user logged in on the controlling terminal of the process. For
most purposes, it is more useful to use the environment variables LOGNAME or USERNAME

VLITS II YEAR STUDENTS &STAFF


PYTHON 163

to find out who the user is, or pwd.getpwuid(os.getuid( ))[0] to get the login name of the current
real user id.

 os.getpgid(pid)
Return the process group id of the process with process id pid. If pid is 0, the process
group id of the current process is returned.

 os.getpgrp( )
Return the id of the current process group.

 os.getpid( )
Return the current process id.

 os.getppid( )
Return the parent‘s process id. When the parent process has exited, on Unix the id
returned is the one of the init process (1), on Windows it is still the same id, which may be
already reused by another process.

 os.getpriority(which, who)
Get program scheduling priority. The value which is one of PRIO_PROCESS,
PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for
PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A
zero value for who denotes (respectively) the calling process, the process group of the calling
process, or the real user ID of the calling process.
Hence, we can also find various of functions to work with operating system interface.

String pattern matching


Regular expressions are powerful tool for various kinds of string manipulation.
 These are basically a special string text string i.e., used for describing a search pattern to
extract information from text such as code, files, log spread sheets or even documents.
 Regular expressions are domain specific language [DSL] i.e., present as a library in most of
the modern programming languages.
 Regular expressions are a special sequence of characters that helps to match or find strings
in another string.

How regular expressions are accessed in python?


In python regular expressions can be accessed using the ‗re‘ module which comes as a
part of standard library.

Now let us discuss some important concepts in ‗re‘ module.


1. match( )
syntax : re.match(pattern, string, flags=0)
In the above syntax flag field is optional.

VLITS II YEAR STUDENTS &STAFF


PYTHON 164

Here is the descriptions of the parameters:

The re.match function returns a match object on success, None on failure.We usegroup(num) or
groups() function of match object to get matched expression.
Table:

Example 1:

2.search( )
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)
Example 1:

VLITS II YEAR STUDENTS &STAFF


PYTHON 165

 re.fullmatch (pattern, string, flags=0)


If the whole string matches the regular expression pattern, return a corresponding match
object. Return none if the string does not match the pattern; note that this is different from a
zero-length match.

 re.split (pattern, string, maxsplit=0, flags=0)


Split string by the occurrences of pattern. If maxsplit is nonzero, at most maxsplit splits
occur, and the remainder of the string is returned as the final element of the list.

 re.findall (pattern, string, flags=0)


Return all non-overlapping matches of pattern in string, as a list of strings. The string is
scanned left-to-right, and matches are returned in the order found. If one or more groups are
present in the pattern, return a list of groups; this will be a list of tuples if the pattern has
more than one group. Empty matches are included in the result unless they touch the
beginning of another match.

 re.finditer(pattern, string, flags=0)


Return an iterator yielding match objects over all non-overlapping matches for the RE
pattern in string. The string is scanned left-to-right, and matches are returned in the order
found. Empty matches are included in the result unless they touch the beginning of another
match.

 re.sub (pattern, repl, string, count=0, flags=0)


Return the string obtained by replacing the leftmost non-overlapping occurrences of
pattern in string by the replacement repl.

Hence we can also find various number of regular expressions that can be accessed.

Meta characters in regular expressions:


Meta characters make regular expressions more powerful than normal string
methods. They allow us to create regular expressions to represent concepts like ―one or more
repetitions of a vowel.

VLITS II YEAR STUDENTS &STAFF


PYTHON 166

Mathematics
This module is always available. It provides access to the mathematical functions defined
by the C standard.
These functions cannot be used with complex numbers; use the functions of the same
name from the cmath module if you require support for complex numbers. The distinction
between functions which support complex numbers and those which don‘t is made since most
users do not want to learn quite as much mathematics as required to understand complex
numbers. Receiving an exception instead of a complex result allows earlier detection of the
unexpected complex number used as a parameter, so that the programmer can determine how
and why it was generated in the first place.

The following functions are provided by this module. Except when explicitly noted otherwise, all
return values are floats.

 math.ceil(x)
Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a
float, delegates to x.__ceil__( ), which should return an Integral value.
 math.fabs(x)
Return the absolute value of x.
 math.factorial(x)
Return x factorial. Raises ValueError if x is not integral or is negative.
 math.floor(x)
Return the floor of x, the largest integer less than or equal to x. If x is not a float,
delegates to x.__floor__( ), which should return an Integral value.

 math.fmod(x, y)
Python‘s x % y returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python‘s -1e-
100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the
surprising 1e100. For this reason, function fmod() is generally preferred when working with
floats, while Python‘s x % y is preferred when working with integers.

 math.fsum(iterable)
Return an accurate floating point sum of values in the iterable.

 math.gcd(a, b)
Return the greatest common divisor of the integers a and b. If either a or b is
nonzero, then the value of gcd(a, b) is the largest positive integer that divides both a and b.
gcd(0, 0) returns 0.

 math.isfinite(x)
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0
is considered finite.).

 math.isinf(x)
Return True if x is a positive or negative infinity, and False otherwise.

VLITS II YEAR STUDENTS &STAFF


PYTHON 167

 math.isnan(x)
Return True if x is a NaN (not a number), and False otherwise.

 math.ldexp(x, i)
Return x * (2**i). This is essentially the inverse of function frexp( ).

 math.modf(x)
Return the fractional and integer parts of x. Both results carry the sign of x and are
floats.

 math.trunc(x)
Return the Real value x truncated to an Integral (usually an integer).

Power and logarithmic functions

 math.exp(x)
Returns e**x.
 math.expm1(x)
Returns e**x - 1.
 math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way
which is accurate for x near zero.
 math.log2(x)
Return the base-2 logarithm of x. This is usually more accurate than log(x,2)
 math.log10(x)
Return the base-10 logarithm of x. This is usually more accurate than log(x,10)
 math.pow(x,y)
Return x raised to the power y.
 math.sqrt(x)
Return the square root of x.

Trigonometric functions

 math.acos(x)
Return the arc cosine of x, in radians.
 math.asin(x)
Return the arc sine of x, in radians.
 math.atan(x)
Return the arc tangent of x, in radians.
 math.atan2(y, x)
Return atan(y / x), in radians.
 math.cos(x)
Return the cosine of x radians.
 math.hypot(x, y)

VLITS II YEAR STUDENTS &STAFF


PYTHON 168

Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the
origin to point (x, y).
 math.sin(x)
Return the sine of x radians.
 math.tan(x)
Return the tangent of x radians.

Special functions

 math.erf(x)
Return the error function at x.The erf() function can be used to compute traditional
statistical functions such as the cumulative standard normal distribution.
 math.erfc(x)
Return the complementary error function at x. The complementary error function
is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would
cause a loss of significance.
 math.gamma(x)
Return the Gamma function at x.
 math.lgamma(x)
Return the natural logarithm of the absolute value of the Gamma function at x.

Constants

 math.pi
The mathematical constant π = 3.141592…, to available precision.
 math.e
The mathematical constant e = 2.718281…, to available precision.
 math.tau
The mathematical constant τ = 6.283185…, to available precision. Tau is a circle
constant equal to 2π, the ratio of a circle‘s circumference to its radius.
The mathematical constant π = 3.141592…, to available precision.

Internet access
urllib2

The urllib2 module defines functions and classes which help in opening URLs (mostly
HTTP) in a complex world basic and digest authentication, redirections, cookies and more.
The urllib2 module defines the following functions:
 urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

Open the URL url, which can be either a string or a Request object. data may be a string
specifying additional data to send to the server, or None if no such data is needed. Currently
HTTP re uests are the only ones that use data; The optional timeout parameter specifies a time

VLITS II YEAR STUDENTS &STAFF


PYTHON 169

out in seconds for blocking operations like the connection attempt. This actually only works for
HTTP, HTTPS and FTP connections.
This function returns a file-like object with three additional methods:
 geturl( ) : return the URL of the resource retrieved, commonly used to determine if a
redirect was followed
 ·info( ) : return the meta-information of the page, such as headers, in the
form of an mimetools. Message instance (see uick Reference to HTTP Headers)
 getcode( ): return the HTTP status code of the response.
 urllib2.install_opener(opener)
Install an OpenerDirector instance as the default global opener. Installin
opener is only necessary if you want urlopen to use that opener; otherwise, simply
call OpenerDirector.open( ) instead of urlopen( ). The code does notcheck for a real
OpenerDirector, and any class with the appropriate interface will work.
 urllib2.build_opener([handler, …])
Return an OpenerDirector instance, which chains the handlers in the order given.
handlers can be either instances of BaseHandler, or subclasses of BaseHandler (in which case it
must be possible to call the constructor without any parameters). Instances of the following
classes will be in front of the handlers, unless the handlers contain them, instances of them
or subclasses of them.
 stmplib:
The smtplib module defines an SMTP client session object that can be used to send
mail to any Internet machine with an SMTP or ESMTP listener daemon. For details of
SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and
RFC 1869(SMTP Service Extensions).
Example 1:

Example 2:

VLITS II YEAR STUDENTS &STAFF


PYTHON 170

Dates and Times


There are 3 important modules to work out with dates and times. They are:
1. datetime module
2. time module
3. calendar module
datetime module:
The datetime module supplies classes for manipulating dates and times in both simple
and complex ways. While date and time arithmetic is supported, the focus of the
implementation is on efficient attribute extraction for output formatting and manipulation. For
related functionality, see also the time and calendar modules.
The datetime module exports the following constants:

 datetime.MINYEAR
The smallest year number allowed in a date or datetime object. MINYEAR is 1.

 datetime.MAXYEAR
The largest year number allowed in a date or datetime object. MAXYEAR is 9999.

Available Types
 class datetime.date
An idealized naive date, assuming the current Gregorian calendar always was, and always
will be, in effect. Attributes: year, month, and day.

 class datetime.time
An idealized time, independent of any particular day, assuming that every day has exactly
24*60*60 seconds (there is no notion of ―leap seconds‖ here). Attributes: hour, minute,
second, microsecond, and tzinfo.

 class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour, minute, second,
microsecond, and tzinfo.

 class datetime.timedelta
A duration expressing the difference between two date, time, or datetime instances to
microsecond resolution.

 class datetime.tzinfo
An abstract base class for time zone information objects. These are used by the datetime
and time classes to provide a customizable notion of time adjustment (for example, to account
for time zone and/or daylight saving time).

 class datetime.timezone
A class that implements the tzinfo abstract base class as a fixed offset from the UTC.

VLITS II YEAR STUDENTS &STAFF


PYTHON 171

The time Module


There is a popular time module available in Python which provides functions for working
with times and for converting between representations. Here is the list of all available methods −

 time.altzone

The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe, including
the UK). Only use this if daylight is nonzero.

 time.asctime([tupletime])
Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11
18:07:14 2008'.

 time.clock( )
Returns the current CPU time as a floating-point number of seconds. To measure
computational costs of different approaches, the value of time.clock is more useful than
that of time.time().

 time.ctime([secs])
Like asctime(localtime(secs)) and without arguments is like asctime( )

 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t
with the UTC time. Note : t.tm_isdst is always 0

 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a time-tuple t
with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant
secs by local rules).

 time.mktime(tupletime)
Accepts an instant expressed as a time-tuple in local time and returns a floating-
point value with the instant expressed in seconds since the epoch.

 time.sleep(secs)
Suspends the calling thread for secs seconds.

 time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and returns a string
representing the instant as specified by string fmt.

 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')


Parses str according to format string fmt and returns the instant in time-tuple
format.

VLITS II YEAR STUDENTS &STAFF


PYTHON 172

 time.time( )
Returns the current time instant, a floating-point number of seconds since the
epoch.

 time.tzset( )
Resets the time conversion rules used by the library routines. The environment
variable TZ specifies how this is done.

The calendar Module


The calendar module supplies calendar-related functions, including functions to print a
text calendar for a given month or year.
By default, calendar takes Monday as the first day of the week and Sunday as the last one. To
change this, call calendar.setfirstweekday( ) function.

Here is a list of functions available with the calendar module −



 calendar.calendar(year,w=2,l=1,c=6)
o Returns a multiline string with a calendar for year year formatted into three columns
separated by c spaces. w is the width in characters of each date; each line has length
21*w+18+2*c. l is the number of lines for each week.
o
 calendar.firstweekday( ):
Returns the current setting for the weekday that starts each week. By default, when
calendar is first imported, this is 0, meaning Monday.

 calendar.isleap(year)
Returns True if year is a leap year; otherwise, False.

 calendar.leapdays(y1,y2)
o Returns the total number of leap days in the years within range(y1,y2).
o
 calendar.month(year,month,w=2,l=1)
o Returns a multiline string with a calendar for month month of year year, one line per
week plus two header lines. w is the width in characters of each date; each line has length
7*w+6. l is the number of lines for each week.
o
 calendar.monthcalendar(year,month)
o Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of
year year are set to 0; days within the month are set to their day-of-month, 1 and up.
o
 calendar.monthrange(year,month)
o Returns two integers. The first one is the code of the weekday for the first day of the

VLITS II YEAR STUDENTS &STAFF


PYTHON 173

month month in year year; the second one is the number of days in the month. Weekday codes
are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.
o
 calendar.prcal(year,w=2,l=1,c=6)
o Like print calendar.calendar(year,w,l,c).
o
 calendar.prmonth(year,month,w=2,l=1)
o Like print calendar.month(year,month,w,l).
o
 calendar.setfirstweekday(weekday)
o Sets the first day of each week to weekday code weekday. Weekday codes are 0
(Monday) to 6 (Sunday).
o
 calendar.timegm(tupletime)
o The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the
same instant as a floating-point number of seconds since the epoch.
o

Data Compression

 The zlib, gzip and bz2 modules provide essential data and file compression tools. Data
files are often built for speedy processing, and may contain characters which are
meaningless spacing. This extraneous data can be reduced in size, or compressed.
 These modules are very flexible and can be used in a variety of ways by an application
program. The interface to zlib and bz2 are very similar. The interface to gzip is greatly
simplified.
 The zlib and bz2 modules provide essential data compression and decompression
algorithms. Each module provides a compress and decompress function which will
compress a string into a sequence of bytes. For relatively short strings, there may be no
reduction in size.

zlib.compress( string , 〈 level 〉)


Compress the given string . The level provides a speed vs. size tradeoff: a value of 1 is
very fast, but may not compress very well; a value of 9 will be slower but provide the best
compression. The default value for level is 6.
zlib.decompress( string)
Decompress the given string .
bz2.compress
Compress the given string . The level provides a speed vs. size tradeoff: a value of 1 is very fast,
but may not compress very well; a value of 9 will be slower but provide the best compression.
The default value for level is 9.
bz2.decompress
Decompress the given string .
In addition to simple compression and decompression, zlib provides some additional features for
computing various kinds of checksums of the data.

VLITS II YEAR STUDENTS &STAFF


PYTHON 174

zlib.adler32( string )
Compute the 32-bit Adler checksum of the given string .

zlib.crc32( string)
Compute the 32-bit CRC (Cyclic Redundancy Check) checksum the given string .

Let us consider the following example:

Multithreading
Running several threads is similar to running several different programs concurrently, but with
the following benefits −
 Multiple threads within a process share the same data space with the main thread and
can therefore share information or communicate with each other more easily than if
they were separate processes.
 Threads sometimes called light-weight processes and they do not require much
memory overhead; they are cheaper than processes.
 A thread has a beginning, an execution sequence, and a conclusion. It has an
instruction pointer that keeps track of where within its context it is currently running.
 It can be pre
 -empted (interrupted).It can temporarily be put on hold (also known as sleeping)
while other threads are running - this is called yielding.

Starting a new thread


To spawn another thread, you need to call following method available in thread module –
thread.start_new_thread(function,args[,kwargs])

 This method call enables a fast and efficient way to create new threads in both Linux
and Windows.
 The method call returns immediately and the child thread starts and calls function
with the passed list of args. When function returns, the thread terminates.
 Here, args is a tuple of arguments; use an empty tuple to call function without
passing any arguments. kwargs is an optional dictionary of keyword arguments.

Consider the following example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 175

Although it is very effective for low-level threading, but the thread module is very limited
compared to the newer threading module.

The threading module


The newer threading module included with Python 2.4 provides much more powerful,
high-level support for threads than the thread module discussed in the previous section.
The threading module exposes all the methods of the thread module and provides some
additional methods –

threading.activeCount( ) Returns the number of thread objects that are active.

threading.currentThread( ) Returns the number of thread objects in the caller's thread


control.

threading.enumerate( ) Returns a list of all thread objects that are currently active.

In addition to the methods, the threading module has the Thread class that implements
threading.

The methods provided by the Thread class are as follows:

VLITS II YEAR STUDENTS &STAFF


PYTHON 176

Method Description
run ( ) This method is the entry point for a thread.
start( ) This method starts a thread by calling the run method.
join([time]) This method waits for threads to terminate.
isAlive( ) This method checks whether a thread is still executing.
getName( ) This method returns the name of a thread.
setName( ) This method sets the name of a thread.

GUI Programming
 Graphical User Interfaces (GUI‘s) provide a rich environment in which information can
be exchanged between a user and the computer.
 GUI‘s are not limited to simply displaying text and reading text from the keyboard.
GUI‘s enable users to control the behavior of a program by performing actions such as
using the mouse to drag or click on graphical objects. GUI‘s can make using programs
much more intuitive and easier to learn since they provide users with immediate visual
feedback that shows the effects of their actions.
 tkinter is primarily designed for creating GUI‘s. In fact, IDLE is built using tkinter.
Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
 Tkinter –
Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look this option in this chapter.
 wxPython –

This is an opensourcePython interface for wxWindows http://wxpython.org.


JPython − JPython is a Python port for Java which gives Python scripts seamless access
to Java class libraries on the local machine http://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-
oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
 Import the Tkinter module.
 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the user.
Consider the following example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 177

The output will be as follows:

Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.

We present these widgets as well as a brief description in the following table –

S.No. Operator & Description

1 Button
The Button widget is used to display buttons in your application.

2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.

3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.

4 Entry
The Entry widget is used to display a single-line text field for accepting values from a
user.

5 Frame
The Frame widget is used as a container widget to organize other widgets.

6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.

VLITS II YEAR STUDENTS &STAFF


PYTHON 178

7 Listbox
The Listbox widget is used to provide a list of options to a user.

8 Menubutton
The Menubutton widget is used to display menus in your application.

9 Menu
The Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.

10 Message
The Message widget is used to display multiline text fields for accepting values from a
user.

11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The
user can select only one option at a time.

12 Scale
The Scale widget is used to provide a slider widget.

13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list
boxes.

14 Text
The Text widget is used to display text in multiple lines.

15 Toplevel
The Toplevel widget is used to provide a separate window container.

16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.

17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.

18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.

19 tkMessageBox
This module is used to display message boxes in your applications.

VLITS II YEAR STUDENTS &STAFF


PYTHON 179

Turtle Graphics
 There are many Python packages that can be used to create graphics and GUI‘s. Two
graphics modules, called turtle and tkinter, come as a part of Python‘s standard library.
However, we will focus on the turtle module that is primarily used as a simple graphics
package but can also be used to create simple GUI‘s.
 The turtle module is an implementation of turtle graphics and uses tkinter for the creation
of the underlying graphics.
 Turtle graphics dates back to the 1960‘s and was part of the Logo programming
language.

Importing tutle graphics

In order to start using turtle graphics, we need to import the turtle module.
The methods used to draw a turtle graphic are as follows:

Method Description

fd( ) The fd( ) method is a shorthand for the forward() method—the two
methods are identical. fd( ) takes one integer argument that specifies
the number of units you want to move the turtle forward in the
direction of the current heading.If you provide a negative argument,
the turtle moves backwards the specified amount. Alternatively, to
move backward one can call either backward( ), back(), or bk( ).
hideturtle( ) This hides the image that currently represents the turtle. In fact, you
can continue to create lines even when the turtle‘s shape is hidden,
but you will not be able to see the turtle‘s current position nor its
heading.
penup ( ) It lifts up the pen.

pendown( ) It lifts down the pen.

showturtle( ) If you want to see the turtle, simply issue the command.

left(n) or lt(n) It turns the turtle to the left by ‗n‘ number of degrees given as the
argument.
right(n) or rt(n) It turns the turtle to the right by ‗n‘ number of degrees given as the
argument.
setheading() or It sets the absolute heading of the turtle. A heading of 0 is
seth() horizontally to the right (i.e., east), 90 is up (i.e., north), 135 is up
and to the left (i.e., northwest), and so on.

setposition( )or setposition()‘s arguments are the desired x and y values. The change
setpos( ) or goto( ) of position does not affect the turtle‘s heading.

VLITS II YEAR STUDENTS &STAFF


PYTHON 180

clear( ) clears the drawing from the graphics window but it leaves the
turtle in its current position with its current heading.
reset( ) reset() clears the drawing and also returns the turtle to its starting
position in the center of the screen.
circle( ) This can be used to tell the turtle to draw a complete circle or only a
part of a circle, i.e., an arc. The circle() method has one mandatory
argument which is the radius of the circle. Optional arguments
specify the ―extent,‖ which is the degrees of arc that are drawn, and
the ―steps,‖ which are the number of straight-line segments used to
approximate the circle.
If the radius is positive, the circle is drawn (starting from the current
position) by turning to the left (counterclockwise). If the radius is
negative, the circle is drawn(starting from the current position) by
turning to the right (clockwise).

speed() method for which the argument specifies the


speed( ) speed as an integer between 0 and 10. A value of 1 is the slowest
speed. Speeds generally increase with increasing arguments so that 2
is faster than 1, three is faster than 2, and so on. However, rather
than 10 being be fastest speed, it is actually the second to the fastest
speed—0 is the fastest
speed. The default speed is 3.

color ( ) We can change the color of turtle‘s pen using this method.

pensize( ) We can change the thickness of a turtle pen using this method.
passing it with an integer argument that specifies the thickness.

Now let us consider an example:

VLITS II YEAR STUDENTS &STAFF


PYTHON 181

The output will be as follows:

Testing
Software testing is an investigation conducted to provide stakeholders with information
about the quality of the software product or service under test. Software testing can also provide
an objective, independent view of the software to allow the business to appreciate and
understand the risks of software implementation. Test techniques include the process of
executing a program or application with the intent of finding software bugs (errors or other
defects), and verifying that the software product is fit for use.
Software testing involves the execution of a software component or system component to
evaluate one or more properties of interest. In general, these properties indicate the extent to
which the component or system under test:

 meets the requirements that guided its design and development.


 responds correctly to all kinds of inputs.
 performs its functions within an acceptable time.
 is sufficiently usable.
 can be installed and run in its intended environments, and achieves the general result its
stakeholders desire.
The job of testing is an iterative process as when one bug is fixed, it can illuminate other, deeper
bugs, or can even create new ones.

VLITS II YEAR STUDENTS &STAFF


PYTHON 182

Software testing can provide objective, independent information about the quality of software
and risk of its failure to users or sponsors.Software testing can be conducted as soon as
executable software (even if partially complete) exists.

Why testing is required?


Software testing is necessary because we all make mistakes.some of these mistakes are
unimportant and some of them are dangerous.software testing is necessary because of the
following reasons:
 Testing will give confidence for the software development company that the software
will work satisfactorily in client environment.
 Testing will improve the software quality.
 Testing will also reduces the maintanance cost.
 Testing is necesasary inorder to provide the facilities to the customers like the delivery of
the high quality product or software with lower maintenance cost with more
accurate,consistant and reliable results.
 Testing is required for an effective performance of an software product.It is required to
stay top in the business.

Basic concepts of testing


Testing are classifying into following types:

Installation testing
An installation test assures that the system is installed correctly and working at actual
customer's hardware.

Compatibility testing
A common cause of software failure (real or perceived) is a lack of its compatibility with
other application software, operating systems (or operating system versions, old or new. This
results in the unintended consequence that the latest work may not function on earlier versions of
the target environment, or on older hardware that earlier versions of the target environment was
capable of using. Sometimes such issues can be fixed by proactively abstracting operating
system functionality into a separate program module or library.

Smoke and sanity testing


Sanity testing determines whether it is reasonable to proceed with further testing.
Smoke testing consists of minimal attempts to operate the software, designed to determine
whether there are any basic problems that will prevent it from working at all. Such tests can be
used as build verification test.

Regression testing
Regression testing focuses on finding defects after a major code change has occurred.
Specifically, it seeks to uncover software regressions, as degraded or lost features, including old
bugs that have come back. Typically, regressions occur as an unintended consequence of
program changes, when the newly developed part of the software collides with the previously
existing code. Common methods of regression testing include re-running previous sets of test
cases and checking whether previously fixed faults have re-emerged.

VLITS II YEAR STUDENTS &STAFF


PYTHON 183

Acceptance testing
Acceptance testing can mean one of two things:
 A smoke test is used as an acceptance test prior to introducing a new build to the main
testing process, i.e., before integration or regression.
 Acceptance testing performed by the customer, often in their lab environment on their
own hardware, is known as user acceptance testing (UAT). Acceptance testing may be
performed as part of the hand-off process between any two phases of development

Alpha testing
Alpha testing is simulated or actual operational testing by potential users/customers or an
independent test team at the developers' site. Alpha testing is often employed for off-the-shelf
software as a form of internal acceptance testing, before the software goes to beta testing.

Functional vs non-functional testing


Functional testing refers to activities that verify a specific action or function of the code.
These are usually found in the code requirements documentation. Functional tests tend to answer
the question of "can the user do this" or "does this particular feature work."
Non-functional testing refers to aspects of the software that may not be related to a specific
function or user action, such as scalability or other performance, behavior under certain
constraints, or security.

Continuous testing
Continuous testing is the process of executing automated tests as part of the software
delivery pipeline to obtain immediate feedback on the business risks associated with a software
release candidate. Continuous testing includes the validation of both functional requirements and
non-functional requirements.

Destructive testing
Destructive testing attempts to cause the software or a sub-system to fail. It verifies that
the software functions properly even when it receives invalid or unexpected inputs.

Software performance testing


Performance testing is generally executed to determine how a system or sub-system
performs in terms of responsiveness and stability under a particular workload. It can also serve to
investigate, measure, validate or verify other quality attributes of the system, such as scalability,
reliability and resource usage.

Usability testing
Usability testing is to check if the user interface is easy to use and understand. It is
concerned mainly with the use of the application.

Accessibility testing
Accessibility testing may include compliance with standards such as:
 Americans with Disabilities Act of 1990
 Section 508 Amendment to the Rehabilitation Act of 1973

VLITS II YEAR STUDENTS &STAFF


PYTHON 184

 Web Accessibility Initiative (WAI) of the World Wide Web Consortium (W3C)

Security testing
Security testing is essential for software that processes confidential data to prevent
system intrusion by hackers.

Development testing
Development Testing is a software development process that involves synchronized
application of a broad spectrum of defect prevention and detection strategies in order to reduce
software development risks, time, and costs. It is performed by the software developer or
engineer during the construction phase of the software development lifecycle.

A/B testing
A/B testing is basically a comparison of two outputs, generally when only one variable
has changed: run a test, change one thing, run the test again, compare the results. This is more
useful with more small-scale situations, but very useful in fine-tuning any program.

Concurrent testing
In concurrent testing, the focus is on the performance while continuously running with
normal input and under normal operational conditions, as opposed to stress testing, or fuzz
testing. Memory leak, as well as basic faults are easier to find with this method.

Conformance testing or type testing


In software testing, conformance testing verifies that a product performs according to its
specified standards. Compilers, for instance, are extensively tested to determine whether they
meet the recognized standard for that language.

Testing process
Traditional waterfall development model
A common practice of software testing is that testing is performed by an independent
group of testers after the functionality is developed, before it is shipped to the customer.This
practice often results in the testing phase being used as a project buffer to compensate for project
delays, thereby compromising the time devoted to testing.

Testing methods
The box approach
Software testing methods are traditionally divided into white- and black-box testing.
These two approaches are used to describe the point of view that a test engineer takes when
designing test cases.

White box testing


White-box testing (also known as clear box testing, glass box testing, transparent box
testing and structural testing, by seeing the source code) tests internal structures or workings of a

VLITS II YEAR STUDENTS &STAFF


PYTHON 185

program, as opposed to the functionality exposed to the end-user. In white-box testing an internal
perspective of the system, as well as programming skills, are used to design test cases.

Techniques used in white-box testing include:


 API testing – testing of the application using public and private APIs (application
programming interfaces)
 Code coverage – creating tests to satisfy some criteria of code coverage (e.g., the test
designer can create tests to cause all statements in the program to be executed at least
once)
 Fault injection methods – intentionally introducing faults to gauge the efficacy of testing
strategies
 Mutation testing methods
 Static testing methods

Black box testing


Black-box testing treats the software as a "black box", examining functionality without
any knowledge of internal implementation, without seeing the source code. The testers are only
aware of what the software is supposed to do, not how it does it. Black-box testing methods
include: equivalence partitioning, boundary value analysis, all-pairs testing, state transition
tables, decision table testing, fuzz testing, model-based testing, use case testing, exploratory
testing and specification-based testing.

Visual testing:
The aim of visual testing is to provide developers with the ability to examine what was
happening at the point of software failure by presenting the data in such a way that the developer
can easily find the information she or he requires, and the information is expressed clearly.

Gray box testing


Grey-box testing (American spelling: gray-box testing) involves having knowledge of
internal data structures and algorithms for purposes of designing tests, while executing those
tests at the user, or black-box level.

Testing levels
There are generally four recognized levels of tests: unit testing, integration testing,
component interface testing, and system testing. Tests are frequently grouped by where they are
added in the software development process, or by the level of specificity of the test.

Integration testing
Integration testing is any type of software testing that seeks to verify the interfaces
between components against a software design.Software components may be integrated in an
iterative way or all together ("big bang")..

Integration testing works to expose defects in the interfaces and interaction between
integrated components (modules).

VLITS II YEAR STUDENTS &STAFF


PYTHON 186

Component interface testing


The practice of component interface testing can be used to check the handling of data
passed between various units, or subsystem components, beyond full integration testing between
those units.

System testing
System testing tests a completely integrated system to verify that the system meets its
requirements. For example, a system test might involve testing a logon interface, then creating
and editing an entry, plus sending or printing results, followed by summary processing or
deletion (or archiving) of entries, then logoff.

Unit testing in python


Unit testing refers to tests that verify the functionality of a specific section of code,
usually at the function level. In an object-oriented environment, this is usually at the class level,
and the minimal unit tests include the constructors and destructors.

These types of tests are usually written by developers as they work on code (white-box style), to
ensure that the specific function is working as expected. One function might have multiple tests,
to catch corner cases or other branches in the code. Unit testing alone cannot verify the
functionality of a piece of software, but rather is used to ensure that the building blocks of the
software work independently from each other.

It is performed by the software developer or engineer during the construction phase of the
software development lifecycle. Unit testing aims to eliminate construction errors before code is
promoted to QA; this strategy is intended to increase the quality of the resulting software as well
as the efficiency of the overall development and QA process.

Example of unit testing:

VLITS II YEAR STUDENTS &STAFF


PYTHON 187

Advantages
The goal of unit testing is to isolate each part of the program and show that the individual
parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy.
As a result, it affords several benefits.
 Unit testing finds problems early in the development cycle. This includes both bugs in the
programmer's implementation and flaws or missing parts of the specification for the unit.
 Unit testing allows the programmer to refactor code or upgrade system libraries at a later
date, and make sure the module still works correctly (e.g., in regression testing).
 Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-
up testing style approach.
 It provides a sort of living documentation of the system. Developers looking to learn
what functionality is provided by a unit, and how to use it.
 Each unit test can be seen as a design element specifying classes, methods, and
observable behaviour.

Disadvantages
 Testing will not catch every error in the program, because it cannot evaluate every
execution path in any but the most trivial programs.
 Software testing is a combinatorial problem.
 Another challenge related to writing the unit tests is the difficulty of setting up realistic
and useful tests.
 It is essential to keep careful records not only of the tests that have been performed, but
also of all changes that have been made to the source code of this or any other unit in the
software.
 It is also essential to implement a sustainable process for ensuring that test case failures
are reviewed regularly and addressed immediately.

Writing Test cases


A well-written test case should allow any tester to understand and execute the test.
When writing test cases, it‘s important to put yourself in the user‘s shoes and include all the
necessary details. Putting forth the extra effort to write good test cases upfront will save you
time and effort further down the road.
 Writing test cases – especially a high volume of them at one time – can be a time
consuming task.
 TestLodge makes it easy to write high quality test cases and keep them organized. Here,
we‘ve outlined some tips on how to write test cases, along with a sample of a test case at
the end of this article.

How to write test cases for software?


Use a Strong Title
 A good test case starts with a strong title. As a best practice, it‘s good to name the test
case along the same lines as the module which you‘re testing.
 For example, if you‘re testing the login page, include ―Login Page‖ within the title of the
test case.

VLITS II YEAR STUDENTS &STAFF


PYTHON 188

Include a Strong Description


The description should tell the tester what they‘re going to test and include any other
pertinent information such as the test environment, test data, and preconditions/assumptions.

Include Assumptions and Preconditions


You should include any assumptions that apply to the test and any preconditions that
must be met prior to the test being executed.
 This information can include which page the user should start the test on, dependencies
on the test environment, and any special setup requirements that must be done before
running the test.
 This information also helps keep the test steps short and concise.

Keep the Test Steps Clear and Concise


The test steps should include the data and information on how to execute the test. This is
perhaps the most important part of a test case. Keep this section clear and concise, but don‘t
leave out any necessary details.

Include the Expected result


The expected result tells the tester what they should experience as a result of the test
steps. This is how the tester determines if the test case is a ―pass‖ or ―fail‖.

Make it Reusable
A good test case is reusable and provides long-term value to the software testing
team. When writing a test case, keep this in mind. You can save time down the road by re-using
the test case instead of re-writing it.

Writing test cases in python


Writing tests for Python is much like writing tests for your own code. Tests need to be
thorough, fast, isolated, consistently repeatable, and as simple as possible. We try to have tests
both for normal behaviour and for error conditions. Tests live in the Lib/test directory, where
every file that includes tests has a test_ prefix.

 One difference with ordinary testing is that you are encouraged to rely on the test.support
module. It contains various helpers that are tailored to Python‘s test suite and help
smooth out common problems such as platform differences, resource consumption and
cleanup, or warnings management. That module is not suitable for use outside of the
standard library.
 When you are adding tests to an existing test file, it is also recommended that you study
the other tests in that file; it will teach you which precautions you have to take to make
your tests robust and portable.

TestCase offers many assertion methods (assertEqual, assertAlmostEqual, assertTrue etc.)

VLITS II YEAR STUDENTS &STAFF


PYTHON 189

Running tests
The unittest.main method will look for all classes derived from TestCase that have been
imported.It runs all tests inside them and reports.

Typically, you will find main() called in a separate code block:

you can run Python test files with unittest without calling main( ):

VLITS II YEAR STUDENTS &STAFF


PYTHON 190

VLITS II YEAR STUDENTS &STAFF

You might also like