Professional Documents
Culture Documents
Complete Python WITH HEADER Final - Review
Complete Python WITH HEADER Final - Review
Complete Python WITH HEADER Final - Review
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
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
1.INTRODUCTION
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.
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.
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.
The above programming code makes us feel better to understand it easily that this code is about
to add two numbers and prints it.
5.The main need of python is that it is used for Backend Web Development.
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:
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.
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
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.
This will executes our script code by restarting into python IDLE shell .For example:
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:
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‘.
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.
Example: In the below example, str (b) converts the integer data type to string data type .
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‖.
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.
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
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:
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:
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:
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
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:
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.
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.
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.
We can even format strings like the printf() style used in c programming language. We
use the % operator to accomplish this.
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.
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.
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
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 ?
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.
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
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.
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.
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.
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.
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
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.
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:
[] 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
not in Membership - Returns true if a character does not „m‟ not in a will
exist in the given string give True
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 .
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.
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.
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.
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.
Comparision operators
Following table holds a=10 and b=20
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.
Example:
output:
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
Example :
Output:
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.
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:
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
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
Example:
Example
if-elif-else statement
syntax:
if (boolean expression 1):
Statements_1
elif(boolean expression 2):
Statements_2
else:
Statements_3
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:
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:
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.
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.
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
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.
Example:
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.
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.
Data structures
Lists-operations,slicing,methods
Tuples
Sets
Dictionaries
Sequences
Comprehensions
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.
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:
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.
Example:
list1=[1,2,3,4,5,6,7,8,9].
Memory diagram for list1:
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.
k=[1,2,3,4,5,6,7]
Using append( )
Syntax:
list name.append(argument)
Consider k=[1,2,3,4,5,6,7]
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:
Now the value which is stored at index 2 in the memory changes from 3 to 5.
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.
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.
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:
Using list( )
Syntax:
variable.split( )
List operations
There exits several operation on lists. Few operations are explained below.
List methods
Python has various methods to help programmers work efficiently with lists.
Some of these methods are summarized in below table
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.
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.
If you want to create a tuple with a single element it is a bit tricky, you must use the comma:
Note that you can concatenate tuples and use augmented assigenment (*=, +=):
>>> s1 = (1,0)
>>> s1 += (1,)
>>> s1
(1, 0, 1)
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.
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.
Updating tuples
we can update values of a list, let‘s see the example whether updating is possible in tuples.
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.
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.
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.
Take elements in the tuple and return a new sorted list (does not sort the tuple
sorted( )
itself).
Example:
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.
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.
count( ) method
count( ) method gives the frequency of a element in the tuple.count( ) takes exactly
only one argument.
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
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.
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:
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( ).
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
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( ).
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( ).
Method Description
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.
Return a new sorted list from elements in the set(does not sort the set
sorted( )
itself).
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.
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.
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.
Dictionary Methods
Python includes following dictionary methods –
SN Methods with Description
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
10. dict.pop(key,default=None)-removes the item with key and return its value or d.
12 dict.popitem( )-remove and return arbitary item .raises keyerror if key is not found.
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.
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.
Types of sequences
Strings:
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).
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.
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.
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.
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
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.
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.
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..
Syntax:
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:
Without arguments
Syntax:
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.
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.
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.
Arguments are declared in the function definition. While calling the function, you can
pass the values for that args as shown below.
Passing arguments can be clearly understood by the following types of function arguments.
In python,arguments are passed by assignment.
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:
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:
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.
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]
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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:
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:
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
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‖.
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.
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.
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.
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
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.
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.
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
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.
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.
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
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..,
dir ( )Parameters
The dir( ) takes maximum of one object.
object (optional) - dir( ) attempts to return all attributes of this object.
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.
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 greater than or equal to one version and less than another.
pip install 'someproject>=1,<2'
Upgrading packages
Upgrade an already installed someproject to the latest from PyPI.
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.
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.
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 −
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.
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.
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.
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.
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
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.
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( )
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
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.
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)
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:
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
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.
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.
In c++ and java constructor name should be same as class name,but in python it is
__init__.
Now you can directly define separate attribute values for separate objects. For example,
Example:
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.
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.
Single inheritance
The process of deriving only one class from a parent class is called as single inheritance.
Single inheritance
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.
Syntax:
Multilevel inheritance
In multilevel inheritance, features of the base class and the derived class is inherited into the new
derived class.
Syntax:
Here, Derived1 is derived from Base, and Derived2 is derived from Derived1.
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.
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:
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:
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.
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:
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.
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.
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:
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]]]
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.
Re-raising Exceptions
We can also re-raise our exceptions in python.
Syntax:
try:
raise ExceptionName
except ExceptionName:
raise #re-raising exception
Testing
Why testing is required?
Basi concepts of testing
Unit testing in python
Writing test cases
Running tests
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( )
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.
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).
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
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.
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:
Hence we can also find various number of regular expressions that can be accessed.
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.
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).
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)
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
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:
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.
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.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.
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
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.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 .
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.
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.
Although it is very effective for low-level threading, but the thread module is very limited
compared to the newer threading module.
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.
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 –
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
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.
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.
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.
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.
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.
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).
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.
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:
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
you can run Python test files with unittest without calling main( ):