Python Programming
Python Programming
UNIT-I
Introduction:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985 – 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL).Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not
after Python-the snake.
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been back ported to
beCompatible with the version 2.7.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.
Python Features:
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and
crossplatform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC,Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than
shell scripting.
Apart from the above-mentioned features, Python has a big list of good features.
On-line games
Web services
Applications
Science
Instrument control
Embedded systems
Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on
www.python.org/downloads/windows
Variable Description
It has a role similar to PATH. This variable tells the Python
interpreter where to locate the module files imported into a
PYTHONPATH program. It should include the Python source library
directory and the directories containing Python source code.
PYTHONPATH is sometimes, preset by the Python installer.
It contains the path of an initialization file containing Python
PYTHONSTARTUP source code. It is executed every time you start the interpreter. It
is named as .pythonrc.py in Unix and it contains commands that
load utilities or modify PYTHONPATH.
The Python Package Index lists thousands of third party modules for Python.
JSON
E-mail processing.
BeautifulSoup, an HTML parser that can handle all sorts of oddball HTML.
IPython is a powerful interactive shell that features easy editing and recording of
a work session, and supports visualizations and parallel computing.
The Software Carpentry Course teaches basic skills for scientific computing,
running bootcamps and providing open-access teaching materials.
3. Education
Python is a superb language for teaching programming, both at the introductory
level and in more advanced courses.
The Education Special Interest Group is a good place to discuss teaching issues.
4. Desktop GUIs
The Tk GUI library is included with most binary distributions of Python.
Some toolkits that are usable on several platforms are available separately:
wxWidgets
GTK+
5. Software Development
Python is often used as a support language for software developers, for build
control and management, testing, and in many other ways.
Buildbot and Apache Gump for automated continuous compilation and testing.
1. Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
command line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
The Python language has many similarities to Perl, C, and Java. However, there are
some definite differences between the languages.
First Python Program
Let us execute the programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt-
on Linux:
$ python
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit
(Intel)] on win32
Type the following text at the Python prompt and press Enter-
If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result-
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.
Let us write a simple Python program in a script. Python files have the
extension.py. Type the following source code in a test.py file.
print("Hello, Python!")
On Linux
$ python test.py
On Windows
C:\Python34>Python test.py
This produces the following result-
Hello, Python!
Variables:
Variables are nothing but reserved memory locations to store values. It means that
when you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to the variables, you can store integers, decimals or characters in these
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. For
example-
#!/usr/bin/python3
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
100
1000.0
John
Multiple Assignment:
a= b = c = 1
Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable
c.
Keywords/Reserve Words:
The following list shows the Python keywords. These are reserved words and you
cannot use them as constants or variables or any other identifier names. All the
Python keywords contain lowercase letters only.
and exec not
as finally or
continue If return
del in while
elif is with
except
Python does not use braces({}) to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example
if True:
print ("True")
else:
print ("False")
If True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with the same number of spaces
would form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the
use of the line continuation character (\) to denote that the line should continue.
For example
total = item_one + \
item_two + \
item_three
The statements contained within the [], {}, or () brackets do not need to use the
line continuation character. For example
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all
the following are legal
word = 'word'
sentence = "This is a sentence."
Paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment
and the Python interpreter ignores them.
# First comment
print ("Hello, Python!") # second comment
You can also type a comment on the same line after a statement or expression
Python does not have multiple-line commenting feature. You have to comment each
line individually as follows-
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
a=5
In the second print() statement, we can notice that a space was added between
the stringand the value of variable a.This is by default, but we can change it.
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can
be done by using the str.format() method. This method is visible to any string
object.
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in
which it is printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
Python Input
The value of variables were defined or hard coded into the source code. To
allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this.
The syntax for input() is
input([prompt])
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.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But it takes
it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
UNIT-II
Standard Data Types:
The data stored in memory can be of many types. 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.
Python has five standard data types-
Numbers
String
List
Tuple
Dictionary
Python Numbers
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 three different numerical types –
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0
in the beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Boolenas:
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively
Boolean Expressions
Compound boolean expressions short circuit
and and or return one of the elements in the expression
Note that when None is returned the interpreter does not print
anything
>>> True and False
False
>>> False or True
True
>>> 7 and 14
14
>>> None and 2
>>> None or 2
2
Operators:
Operators are the constructs, which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called the operator.
Types of Operator
Python language supports the following types of operators-
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Example Program
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c )
c=a*b
print ("Line 3 - Value of c is ", c)
c=a/b
print ("Line 4 - Value of c is ", c )
c=a%b
print ("Line 5 - Value of c is ", c)
a=2
b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
a, b = b, a #values of a and b swapped. a becomes 10, b becomes 21
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program, it produces the following result-
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c=2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
& Binary AND Operator copies a bit to the result, if it (a & b) (means 0000
exists in both operands 1100)
| Binary OR It copies a bit, if it exists in either operand. (a | b) = 61 (means
0011 1101)
^ Binary XOR It copies the bit, if it is set in one operand (a ^ b) = 49 (means
but not both. 0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means
Complement bits. 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary The left operand’s value is moved left by a << = 240 (means
Left Shift the number of bits specified by the right 1111 0000)
operand.
>> Binary The left operand’s value is moved right a >> = 15 (means
Right Shift by the number of bits specified by the 0000 1111)
right operand.
Example
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c=0
c = a & b; # 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))
c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
c = ~a; # -61 = 1100 0011
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2; # 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a >> 2; # 15 = 0000 1111
print ("result of RIGHT SHIFT is ", c,':',bin(c))
When you execute the above program, it produces the following result
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
When you execute the above program, it produces the following result-
Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below:
Example:
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
When you execute the above program, it produces the following result
When you execute the above program, it produces the following result
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Decision-making statements:
Following is the general form of a typical decision making structure found in most of
the programming languages-
Statement Description
if statements An if statement consists of a Boolean expression followed by
one or more statements.
if...else statements An if statement can be followed by an optional else
statement, which executes when the boolean expression is
FALSE.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).
IF Statement
The IF statement is similar to that of other languages. The if statement contains a
logical expression using which the data is compared and a decision is made based
on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. In Python, statements in a block are uniformly
indented after the: symbol. If boolean expression evaluates to FALSE, then the first
set of code after the end of block is executed.
Flow Diagram
Example
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
IF...ELIF...ELSE Statements
The else statement is an optional statement and there could be at the most only
one else statement following if.
Syntax
The syntax of the if...else statement is
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-discount)
In the above example, discount is calculated on the input amount. Rate of discount
is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the
above code is executed, it produces the following result-
Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
Net payable: 1080.0
The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at the most one statement, there can be an arbitrary number of elif
statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but
we can use if..elif...statements to simulate switch case as follows-
Example:
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
When the above code is executed, it produces the following result
Nested IF Statements
There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another
if...elif...else construct.
Syntax
The syntax of the nested if...elif...else construct may be
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
# !/usr/bin/python3
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
When the above code is executed, it produces the following result
Enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
enter number5
not Divisible by 2 not divisible by 3
Python-Loops:
In general, statements are executed sequentially- The first statement in a function
is executed first, followed by the second, and so on. There may be a situation when
you need to execute a block of code several number of times.
Programming languages provide various control structures that allow more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times.
The following diagram illustrates a loop statement.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code.
Python uses indentation as its method of grouping statements.
Flow Diagram
Example
#!/usr/bin/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
When the above code is executed, it produces the following result-
KeyboardInterrupt
The above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else
statement gets executed.
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
Flow Diagram
#!/usr/bin/python3
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")
When the above code is executed, it produces the following result
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Here, we took the assistance of the len() built-in function, which provides the total
number of elements in the tuple as well as the range() built-in function to give us
the actual sequence to iterate over.
The following example illustrates the combination of an else statement with a for
statement that searches for even number in given list.
#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number')
When the above code is executed, it produces the following result
Nested loops
Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.
Syntax
A final note on loop nesting is that you can put any type of loop inside any other
type of loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested-for loop to display multiplication tables from
1-10.
#!/usr/bin/python3
import sys
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()
The print() function inner loop has end=' ' which appends a space instead of
default newline. Hence, the numbers will appear in one row.
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The Loop control statements change the execution from its normal sequence. When
the execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
Python supports the following control statements.
break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the
traditional break statement in C.
The most common use of break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in both while
and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows
break
Flow Diagram
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
The following program demonstrates the use of break in a for loop iterating over a
list. User inputs a number, which is searched in the list. If it is found, then the loop
terminates with the 'found' message.
#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')
continue Statement
The continue statement in Python returns the control to the beginning of the
current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!")
pass Statement:
It is used when a statement is required syntactically but you do not want any
command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The
pass statement is also useful in places where your code will eventually go, but has
not been written yet i.e. in stubs).
Syntax
Pass
Example
#!/usr/bin/python3
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
UNIT-III
List
Python offers a range of compound datatypes often referred to as sequences. List is
one of the most frequently used and very versatile datatype used in Python.
It can have any number of items and they may be of different types (integer, float,
string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So,
a list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must
be an integer. We can't use float or other types, this will result into TypeError.
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
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.
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two index that will slice
that portion from the list.
# Output: [1, 4, 6, 8]
print(odd)
# Output: [1, 3, 5, 7]
print(odd)
We can add one item to a list using append() method or add several items
using extend()method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
my_list.clear()
# Output: []
print(my_list)
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Function Description
Return True if all elements of the list are true (or if the list is
all()
empty).
Return True if any element of the list is true. If the list is empty,
any()
return False.
sorted() Return a new sorted list (does not sort the list itself).
What is tuple?
In Python programming, a tuple is similar to a list. 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.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma. The parentheses are optional but is a good practice to write it.
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# parentheses is optional
# Output: <class 'tuple'>
my_tuple = "hello",
print(type(my_tuple))
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts
from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element
other that (6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result
into TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the example
below.
my_tuple = ('p','e','r','m','i','t')
# Output: 'p'
print(my_tuple[0])
# Output: 't'
print(my_tuple[5])
#print(my_tuple[6])
#my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
# Output: 's'
print(n_tuple[0][3])
# nested index
# Output: 4
print(n_tuple[1][1])
When you run the program, the output will be:
p
t
s
4
2. 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.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[7:])
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned.
But, if the element is itself a mutable datatype like list, its nested items can be
changed.
We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])
#my_tuple[1] = 9
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
Method Description
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
Function Description
Return True if all elements of the tuple are true (or if the tuple is
all()
empty).
Take elements in the tuple and return a new sorted list (does not
sorted()
sort the tuple itself).
Method Description
# using dict()
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
Method Description
Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v(defaults to None).
Remove the item with key and return its value or d if key is
pop(key[,d]) not found. If d is not provided and key is not found,
raises KeyError.
UNIT-IV
Functions:
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you
can also create your own functions. These functions are called user-defined functions.
Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
Syntax:
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
Example
The following function takes a string as input parameter and prints it on the standard
screen.
Calling a Function
Defining a function gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is an example to call the
printme() function-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back in
the calling function. For example-
#!/usr/bin/python3
Here, we are maintaining reference of the passed object and appending values in the same
object. Therefore, this would produce the following result-
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this would
produce the following result-
Function Arguments
You can call a function by using the following types of formal arguments-
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows-
#!/usr/bin/python3
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways-
#!/usr/bin/python3
My string
The following example gives a clearer picture. Note that the order of parameters does not
matter.
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
Name: miki
Age 50
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.
#!/usr/bin/python3
Name: miki
Age 50
Name: miki
Age 35
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.
#!/usr/bin/python3
Output is:
10
Output is:
70
60
50
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an
expression.
Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation
by passing function, during invocation for performance reasons.
Syntax
The syntax of lambda function contains only a single statement, which is as follows
lambda[arg1 [,arg2,.....argn]]:expression
#!/usr/bin/python3
Value of total : 30
Value of total : 40
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.
You can return a value from a function as follows-
#!/usr/bin/python3
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python-
Global variables
Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example-
#!/usr/bin/python3
Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file namedaname.py.
Here is an example of a simple module, support.py
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 hello.py, you
need to put the following command at the top of the script-
#!/usr/bin/python3
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result-
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening repeatedly, if multiple imports occur.
For example, to import the function fibonacci from the module fib, use the following
statement-
#!/usr/bin/python3
It is also possible to import all the names from a module into the current namespace by
using the following import statement
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Within a module, the module’s name (as a string) is available as the value of the global
variable __name__. The code in the module will be executed, just as if you imported it,
but with the __name__ set to "__main__".
Add this code at the end of your module-
#!/usr/bin/python3
if __name__ == "__main__":
f=fib(100)
print(f)
When you run the above code, the following output will be displayed.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences-
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation
dependent default.
set PYTHONPATH=c:\python34\lib;
set PYTHONPATH=/usr/local/lib/python
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
#!/usr/bin/python3
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)
The list contains the names of all the modules, variables and functions that are defined in
#!/usr/bin/python3
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can
be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string
containing the module name. For example, to reload hello module, do the following
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has the following line of
source code-
#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same name as above.
They are −
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
#!/usr/bin/python3
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result
Introduction to PIP:
PyPI - the Python Package Index
The Python Package Index is a repository of software for the Python programming
language.
pip is the recommended installer. Below, we’ll cover the most common usage
scenarios.
To install greater than or equal to one version and less than another:
pip install 'SomeProject>=1,<2'
pip is the preferred installer program. Starting with Python 3.4, it is included
by default with the Python binary installers.
A virtual environment is a semi-isolated Python environment that allows
packages to be installed for use by a particular application, rather than being
installed system wide.
venv is the standard tool for creating virtual environments, and has been
part of Python since Python 3.3. Starting with Python 3.4, it defaults to
installing pip into all created virtual environments.
virtualenv is a third party alternative (and predecessor) to venv. It allows
virtual environments to be used on versions of Python prior to 3.4, which
either don’t provide venv at all, or aren’t able to automatically install pip into
created environments.
The Python Packaging Index is a public repository of open source licensed
packages made available for use by other Python users.
the Python Packaging Authority are the group of developers and
documentation authors responsible for the maintenance and evolution of the
standard packaging tools and the associated metadata and file format
standards. They maintain a variety of tools, documentation, and issue
trackers on both GitHub and BitBucket.
distutils is the original build and distribution system first added to the Python
standard library in 1998. While direct use of distutils is being phased out, it
still laid the foundation for the current packaging and distribution
infrastructure, and it not only remains part of the standard library, but its
name lives on in other ways (such as the name of the mailing list used to
coordinate Python packaging standards development).
Basic usage
The standard packaging tools are all designed to be used from the command
line.
The following command will install the latest version of a module and its
dependencies from the Python Packaging Index:
It’s also possible to specify an exact or minimum version directly on the command
line. When using comparator operators such as >, < or some other special character
which get interpreted by shell, the package name and the version should be enclosed
within double quotes:
Imagine you have an application that needs version 1 of LibFoo, but another
application requires version 2. How can you use both these applications? If you install
everything into /usr/lib/python2.7/site-packages (or whatever your platform’s
standard location is), it’s easy to end up in a situation where you unintentionally
upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be? If an
application works, any change in its libraries or the versions of those libraries can
break the application.
Also, what if you can’t install packages into the global site-packages directory? For
instance, on a shared host.
In all these cases, virtual environments can help you. They have their own installation
directories and they don’t share libraries with other virtual environments.
Currently, there are two viable tools for creating Python virtual environments:
UNIT-V
Errors and Exceptions
There are two distinguishable kinds of errors: syntax errors and exceptions
Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
The parser repeats the offending line and displays a little ‘arrow’ pointing at the
earliest point in the line where the error was detected. The error is caused by (or at
least detected at) the token preceding the arrow: in the example, the error is
detected at the function print(), since a colon (':') is missing before it. File name and
line number are printed so you know where to look in case the input came from
ascript.
Exceptions
An exception is an error that happens during the execution of a program. Exception
handling is a construct in some programming languages to handle or deal with
errors automatically. Many programming languages like C++, Objective-C, PHP,
Java, Ruby, Python, and many others have built-in support for exception handling.
useful convention). Standard exception names are built-in identifiers (not reserved
keywords)
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords)
is executed.
If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause
is skipped. Then if its type matches the exception named after the
except keyword, the except clause is executed, and then execution continues
after the try statement.
If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler is found, it is
an unhandled exception and execution stops with a message as shown above.
A try statement may have more than one except clause, to specify handlers for
different exceptions. At most one handler will be executed. Handlers only handle
exceptions that occur in the corresponding try clause, not in other handlers of the
same try statement. An except clause may name multiple exceptions as a
parenthesized tuple, for example:
A class in an except clause is compatible with an exception if it is the same class or a base class
thereof (but not the other way around — an except clause listing a derived class is not compatible
with a base class). For example, the following code will print B, C, D in that order:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
Example:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
The try ... except statement has an optional else clause, which, when present, must
follow all except clauses. It is useful for code that must be executed if the try clause
does not raise an exception. For example:
f.close()
The use of the else clause is better than adding additional code to the try clause
because it avoids accidentally catching an exception that wasn’t raised by the code
being protected by the try ... except statement.
When an exception occurs, it may have an associated value, also known as the
exception’s argument. The presence and type of the argument depend on the
exception type.
Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur.
For example:
The sole argument to raise indicates the exception to be raised. This must be either
an exception instance or an exception class (a class that derives from Exception). If
an exception class is passed, it will be implicitly instantiated by calling its constructor
with no arguments:
If you need to determine whether an exception was raised but don’t intend to handle
it, a simpler form of the raise statement allows you to re-raise the exception:
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
User-defined Exceptions
Programs may name their own exceptions by creating a new exception class.
Exceptions should typically be derived from the Exception class, either directly or
indirectly.
Exception classes can be defined which do anything any other class can do, but are
usually kept simple, often only offering a number of attributes that allow information
about the error to be extracted by handlers for the exception. When creating a
module that can raise several distinct errors, a common practice is to create a base
class for exceptions defined by that module, and subclass that to create specific
exception classes for different error conditions:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
Most exceptions are defined with names that end in “Error,” similar to the naming of
the standard exceptions.
Many standard modules define their own exceptions to report errors that may occur
in functions they define.
Object Oriented Programming 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.
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows
class ClassName:
'Optional class documentation string'
class_suite
Example
Following is an example of a simple Python class
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
The variable empCount is a class variable whose value is shared among all
the instances of a in this class. This can be accessed as Employee.empCount
from inside the class or outside the class.
The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when you create a new
instance of this class.
You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to
the list for you; you do not need to include it when you call the methods.
To create instances of a class, you call the class using class name and pass in
whatever arguments its __init__ method accepts.
This would create first object of Employee class
emp1 = Employee("Abhinay", 2000)
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would
be accessed using class name as follows
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
You can add, remove, or modify attributes of classes and objects at any time
__bases__: A possibly empty tuple containing the base classes, in the order
of their occurrence in the base class list.
For the above class let us try to access all these attributes-
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
Class Inheritance
The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override
data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base
classes to inherit from is given after the class name –
Example
#!/usr/bin/python3
def parentMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
In a similar way, you can drive a class from multiple parent classes as follows
Overriding Methods
You can always override your parent class methods. One reason for overriding
parent's methods is that you may want special or different functionality in your
subclass.
Example
#!/usr/bin/python3
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors. What
happens when you use the plus operator to add them? Most likely Python will yell at
you. You could, however, define the __add__ method in your class to perform vector
addition and then the plus operator would behave as per expectation −
Example
#!/usr/bin/python3
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
will not be directly visible to outsiders.
Example
#!/usr/bin/python3
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the
class name.
You can access such attributes as object._className__attrName. If you would
replace your last line as following, then it works for you-
.........................
print (counter._JustCounter__secretCount)
Python provides two levels of access to the network services. At a low level, you
can access the basic socket support in the underlying operating system, which
allows you to implement clients and servers for both connection-oriented and
connectionless protocols.
Python also has libraries that provide higher-level access to specific application-
level network protocols, such as FTP, HTTP, and so on.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may
communicate within a process, between processes on the same machine, or
between processes on different continents.
port Each server listens for clients calling on one or more ports. A port
may
be a Fixnum port number, a string containing a port number, or the
name of a service.
The socket Module
To create a socket, you must use the socket.socket() function available in the
socket module, which has the general syntax is
Now call the bind(hostname, port) function to specify a port for your service on
the given host.
Next, call the accept method of the returned object. This method waits until a client
connects to the port you specified, and then returns a connection object that
represents the connection to that client.
#!/usr/bin/python3 # This is server.py file
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg='Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
A Simple Client
Let us write a very simple client program, which opens a connection to a given port
12345 and a given host. It is very simple to create a socket client using the
Python's socket module function.
The following code is a very simple client that connects to a given host and port,
reads any available data from the socket, and then exits-
import socket
A Python program can handle date and time in several ways. Converting between
date formats is a common chore for computers. Python's time and calendar
modules help track dates and times.
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in
time are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python, which provides functions for
working with times, and for converting between representations. The function
time.time() returns the current system time in ticks since 12:00am, January 1,
1970(epoch).
Example
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
What is TimeTuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown
below
Index Field Values
0 4-digit year 2016
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
For Example-
>>>import time
>>> print (time.localtime())
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable
form-
The calendar module gives a wide range of methods to play with yearly and
monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ).
#!/usr/bin/python3
import calendar
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
February 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28
each date; each line has length 7*w+6. l is the number of lines for each
week.
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside
month of year year are set to 0; days within the month are set to their
day-ofmonth,1 and up.
7 calendar.monthrange(year,month)
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.
8 calendar.prcal(year,w=2,l=1,c=6)
Like print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
Like print calendar.month(year,month,w,l).
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday
codes are 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
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.
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 (January) to 12
(December).
GUI Programming:
Python provides various options for developing graphical user interfaces (GUIs).
The most important features are listed below.
Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python.
JPython: JPython is a Python port for Java, which gives Python scripts
seamless access to the Java class libraries on the local machine
http://www.jython.org.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a
powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps –
Example
#!/usr/bin/python3
import tkinter # note that module name has changed from Tkinter in Python 2 to
tkinter in Python 3
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a
GUI application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as
well as a brief description in the following table-
Operator Description
Button The Button widget is used to display the buttons in your
application.
Canvas The Canvas widget is used to draw shapes, such as lines,
ovals, polygons and rectangles, in your application.
Checkbutton The Checkbutton widget is used to display a number of
options as checkboxes. The user can select multiple
options at a time.
Entry The Entry widget is used to display a single-line text field
for accepting values from a user.
Frame The Frame widget is used as a container widget to
organize other widgets.
Label The Label widget is used to provide a single-line caption
for other widgets. It can also contain images.
Listbox The Listbox widget is used to provide a list of options to
a user.
Menubutton The Menubutton widget is used to display menus in your
application.
Menu The Menu widget is used to provide various commands
to a user. These commands are contained inside
Menubutton.
Message The Message widget is used to display multiline text fields
for accepting values from a user.
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.
Scale The Scale widget is used to provide a slider widget.
Scrollbar The Scrollbar widget is used to add scrolling capability to
various widgets, such as list boxes.
Text The Text widget is used to display text in multiple lines
Toplevel The Toplevel widget is used to provide a separate window
container.
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.
PanedWindow A PanedWindow is a container widget that may contain
any number of panes, arranged horizontally or vertically.
LabelFrame A labelframe is a simple container widget. Its primary
purpose is to act as a spacer or container for complex
window layouts.
TkMessageBox This module is used to display the message boxes in your
applications.
Multiple threads within a process share the same data space with the main
thread and can therefore share information or communicate with each other
more easily than if they were separate processes.
Threads sometimes called light-weight processes and they do not require
much memory overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an
instruction pointer that keeps track of where within its context it is currently running.
It can be pre-empted (interrupted)
It can temporarily be put on hold (also known as sleeping) while other threads
are running - this is called yielding.
Starting a New Thread
To spawn another thread, you need to call following method available
in thread module:
thread.start_new_thread ( function, args[, kwargs] )
This method call enables a fast and efficient way to create new threads in both Linux
and Windows.
The method call returns immediately and the child thread starts and calls function
with the passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without
passing any arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python
import thread
import time
except:
print "Error: unable to start thread"
while 1:
pass
Turtle Graphics
Turtle graphics is a popular way for introducing programming to kids. It was part of
the original Logo programming language developed by Wally Feurzig and Seymour
Papert in 1966.
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. tkinter is primarily designed for creating GUI’s. In fact, IDLE is built using
tkinter. 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.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give
it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the
direction it is facing, drawing a line as it moves. Give it the command turtle.right(25),
and it rotates in-place 25 degrees clockwise
Examples
A square spiral program:
forward(i)
left(91)
Testing in Python:
Software Testing
Software testing is the process of evaluation a software item to detect differences between
given input and expected output. Also to assess the feature of A software item. Testing
assesses the quality of the product. Software testing is a process that should be done during
the development process. In other words software testing is a verification and validation
process.
Verification
Verification is the process to make sure the product satisfies the conditions imposed at the
start of the development phase. In other words, to make sure the product behaves the way
we want it to.
Validation
Validation is the process to make sure the product satisfies the specified requirements at
the end of the development phase. In other words, to make sure the product is built as per
customer requirements.
There are two basics of software testing: blackbox testing and whitebox testing.
Blackbox Testing
Black box testing is a testing technique that ignores the internal mechanism of the system
and focuses on the output generated against any input and execution of the system. It is
also called functional testing.
Whitebox Testing
White box testing is a testing technique that takes into account the internal mechanism of a
system. It is also called structural testing and glass box testing.
Black box testing is often used for validation and white box testing is often used for
verification.
Types of testing
Unit Testing
Integration Testing
Functional Testing
System Testing
Stress Testing
Performance Testing
Usability Testing
Acceptance Testing
Regression Testing
Beta Testing
Unit Testing
Unit testing is the testing of an individual unit or group of related units. It falls under the
class of white box testing. It is often done by the programmer to test that the unit he/she
has implemented is producing expected output against given input.
Integration Testing
Functional Testing
Functional testing is the testing to ensure that the specified functionality required in the
system requirements works. It falls under the class of black box testing.
System Testing
System testing is the testing to ensure that by putting the software in different
environments (e.g., Operating Systems) it still works. System testing is done with full system
implementation and environment. It falls under the class of black box testing.
Stress Testing
Stress testing is the testing to evaluate how system behaves under unfavorable conditions.
Testing is conducted at beyond limits of the specifications. It falls under the class of black
box testing.
Performance Testing
Performance testing is the testing to assess the speed and effectiveness of the system and
to make sure it is generating results within a specified time as in performance requirements.
It falls under the class of black box testing.
Usability Testing
Usability testing is performed to the perspective of the client, to evaluate how the GUI is
user-friendly? How easily can the client learn? After learning how to use, how proficiently
can the client perform? How pleasing is it to use its design? This falls under the class of
black box testing.
Acceptance Testing
Acceptance testing is often done by the customer to ensure that the delivered product
meets the requirements and works as the customer expected. It falls under the class of black
box testing.
Regression Testing
Beta Testing
Beta testing is the testing which is done by end users, a team outside development, or
publicly releasing full pre-version of the product which is known as beta version. The aim of
beta testing is to cover unexpected errors. It falls under the class of black box testing.
unittest supports test automation, sharing of setup and shutdown code for tests,
aggregation of tests into collections, and independence of the tests from the reporting
framework. The unittest module provides classes that make it easy to support these
qualities for a set of tests.
test fixture
A test fixture represents the preparation needed to perform one or more tests, and
any associate cleanup actions. This may involve, for example, creating temporary
or proxy databases, directories, or starting a server process.
test case
A test case is the smallest unit of testing. It checks for a specific response to a
particular set of inputs. unittest provides a base class, TestCase, which may be
used to create new test cases.
test suite
A test suite is a collection of test cases, test suites, or both. It is used to aggregate
tests that should be executed together.
test runner
A test runner is a component which orchestrates the execution of tests and provides
the outcome to the user. The runner may use a graphical interface, a textual
interface, or return a special value to indicate the results of executing the tests.
Basic example
The unittest module provides a rich set of tools for constructing and running tests.
This section demonstrates that a small subset of the tools suffice to meet the needs
of most users.
Here is a short script to test three string methods:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
An introduction to TestCases
The basic building blocks of unit testing are 'test cases' -- single scenarios that
must be set up and checked for correctness. In PyUnit, test cases are represented
by the TestCase class in the unittest module. To make your own test cases you
must write subclasses of TestCase.
An instance of a TestCase class is an object that can completely run a single test
method, together with optional set-up and tidy-up code.
The testing code of a TestCase instance should be entirely self contained, such that
it can be run either in isolation or in arbitrary combination with any number of other
test cases.
The simplest test case subclass will simply override the runTest method in order to
perform specific testing code:
import unittest
class DefaultWidgetSizeTestCase(unittest.TestCase):
def runTest(self):
widget = Widget("The widget")
assert widget.size() == (50,50), 'incorrect default size'
You can place the definitions of test cases and test suites in the same modules as
the code they are to test (e.g. 'widget.py'), but there are several advantages to
placing the test code in a separate module, such as 'widgettests.py':
The test module can be run standalone from the command line
The test code can more easily be separated from shipped code
There is less temptation to change test code to fit the code it tests without a
good reason
Test code should be modified much less frequently than the code it tests
Tested code can be refactored more easily
Tests for modules written in C must be in separate modules anyway, so why
not be consistent?
If the testing strategy changes, there is no need to change the source code
Of course, the whole point of writing these tests is so that we can run them and
find out if our software is working. The test framework uses 'TestRunner' classes to
provide an environment in which your tests can execute. The most common
TestRunner is TextTestRunner, which can run tests and report the results in textual
form:
runner = unittest.TextTestRunner()
runner.run(widgetTestSuite)
By default, TextTestRunner prints its output to sys.stderr, but this can be changed
by passing a different file-like object to its constructor.
Using TextTestRunner like this is an ideal way to run your tests interactively from
within a Python interpreter session.
The unittest module contains a function called main, which can be used to easily
turn a test module into a script that will run the tests it contains. The main function
uses the unittest.TestLoader class to automatically find and load test cases within
the current module.
Therefore, if you name your test methods using the test* convention described
earlier, you can place the following code at the bottom of your test module:
if __name__ == "__main__":
unittest.main()
Then, when you execute your test module from the command line, all of the tests
contained therein will be run. Run the module with the '-h' option in order to see
the options available.
To run arbitrary tests from the command-line, you can run the unittest module as a
script, giving it the name of an test case or test suite:
There is a graphical front end that you can use in order to run your tests. It is
written using Tkinter, the windowing toolkit shipped with Python on most platforms.
It looks similar to the JUnit GUI.
% python unittestgui.py
or