You are on page 1of 46

OPEN SOURCE SOFTWARE UNIT - VI IV IT

Overview of Python
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python was designed to be highly readable which uses English keywords
frequently where as other languages use punctuation and it has fewer syntactical
constructions than other languages.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the Netherlands.
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 open source language and its source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.

Python Features
Python's feature highlights include:
Easy-to-learn:
Python has relatively few keywords, simple structure, and a clearly defined syntax.
This allows the learners to pick up the language in a relatively short period of time.
Easy-to-read:
Python code is much more clearly defined and understandable. Python does not give
as much flexibility to write obfuscated code as compared to other languages, making it easier
for others to understand our code faster and vice versa.
Free and Open Source:
Python is an example of a FLOSS (Free/Library and Open Source Software). In
simple terms, we can freely distribute copies of this software, read its source code, make
changes to it, and use pieces of it in new free programs. This is one of the reasons why
Python is so good - it has been created and is constantly improved by a community.
High-level Language
When we write programs in Python, we never need to bother about the low-level
details such as managing the memory used by our program, etc.
A broad standard library:
One of Python's greatest strengths is the bulk of the library is very portable and crossplatform compatible on UNIX, Windows and Macintosh.
Interactive Mode:
Support for an interactive mode in which we can enter results from a terminal right to
the language, allowing 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.

1 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Databases:
Python provides interfaces to all major commercial databases like MySQL, DB2,
oracle etc.
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.
Interpreted and Byte Compiled
Python is classified as an interpreted language. Python is actually byte-compiled,
resulting in an intermediate form closer to machine language. This improves Python's
performance, yet allows it to retain all the advantages of interpreted languages.
Object Oriented
Python supports procedure-oriented programming as well as object-oriented
programming. Python has a very powerful but simplistic way of doing OOP, especially when
compared to big languages like C++ or Java.

Obtaining Python
For the most up-to-date and current source code, binaries, documentation, news, etc.,
There is a main Python language site or the PythonLabs Web site:
http://www.python.org
(community home page)
http://www.pythonlabs.com (commercial home page)

Installing Python
Platforms with ready-to-install binaries require only the file download and initiation
of the installation application. If a binary distribution is not available for our platform, we
need to obtain and compile the source code manually.
Python is usually installed in a standard location so that we can find it rather easily.
On Unix machines, the executable is usually installed in /usr/local/bin while the libraries
are in /usr/local/lib/python1.x where the 1.x is the version of Python we are using.
On DOS and Windows, we will usually find Python installed in C:\Python or
C:\Program Files\Python. The standard library files are typically installed in C:\Program
Files\Python\Lib.

Running Python
There are three different ways to start Python.
The simplest way is by starting the interpreter interactively, entering one line of
Python at a time for execution.
Another way to start Python is by running a script written in Python. This is
accomplished by invoking the interpreter on our script application.
Finally, we can run from a graphical user interface (GUI) from within an integrated
development environment (IDE). IDEs typically feature additional tools such as
debuggers and text editors.

2 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Interactive Interpreter from the Command-line
We can enter Python and start coding right away in the interactive interpreter by
starting it from the command line. We can do this from Unix, DOS, or any other system
which provides you a command-line interpreter or shell window.
Unix
To access Python, we will need to type in the full pathname to its location unless we
have added the directory where Python resides to our search path. Common places where
Python is installed include /usr/bin and /usr/local/bin can start the interpreter just by invoking
the name python (or jpython), as in the following:
% python
Once Python has started, we'll see the interpreter startup message indicating version
and platform and be given the interpreter prompt ">>>" to enter Python commands

DOS
To add Python to our search path, we need to edit the C:\autoexec.bat file and add the
full path to where our interpreter is installed. It is usually either C:\Python or C:\Program
Files \Python. From a DOS window, the command to start Python is the same as Unix,
python. The only difference is the prompt, which is C:\>.
C:> python

3 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

Syntax and Style


The Python language has many similarities to Perl, C and Java. However, there are
some definite differences between the languages with respect to statements and their syntaxes
Statements in Python
Some rules and certain symbols are used with regard to statements in Python.
Comments ( # )
Comments are any text to the right of the # symbol and are mainly useful as notes for
the reader of the program.
For example:
print('Hello World') # Note that print is a function
or:
# Note that print is a function
print('Hello World')
Continuation Symbol ( \ )
Python statements are, in general, delimited by NEWLINEs, meaning one statement
per line. Single statements can be broken up into multiple lines by use of the backslash. The
backslash symbol ( \ ) can be placed before a NEWLINE to continue the current statement
onto the next line.
For example
# check conditions
if (weather_is_hot == 1) and \
(shark_warnings == 0) :
send_goto_beach_mesg_to_pager()
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon.
i = 5; print(i)
i = i + 1; print(i)
Multiple Statement Groups as Suites ( : )
Groups of individual statements making up a single code block are called "suites" in
Python. Compound or complex statements, such as if, while, def, and class, are those which
require a header line and a suite. Header lines begin the statement with the keyword and
terminate with a colon ( : ) and are followed by one or more lines which make up the suite.
The combination of a header line and a suite is called as a clause.

4 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

For example
if expression :
suite
elif expression :
suite
else :
suite
Suites Delimited via Indentation
A new code block is recognized when the amount of indentation has increased, and
its termination is signaled by a "dedentation," or a reduction of indentation matching a
previous levels. Code that is not indented, i.e., the highest level of code, is considered the
"main" portion of the script.
For example
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Modules
Each Python script is considered a module. Modules have a physical presence as disk
files. Code that resides in modules may belong to an application (i.e., a script that is directly
executed), or may be executable code in a library-type module that may be "imported" from
another module for invocation.

First Python Program


Interactive Mode Programming
In Interactive mode, python statements can be written directly at the command prompt
itself. If we press ENTER key after writing the python statement, then the given statement is
executed and shows the output. For example
>>> print "Hello, Python!"
The output for the above statement is
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.
5 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


The following is the simple Python program in a script. All python files will have
extension .py. So put the following source code in a test.py file.
print "Hello, Python!";
The following is the command to execute the python script.
$ python test.py
This will produce the following result:
Hello, Python!

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $ and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
Here are following identifier naming convention for Python:
Class names start with an uppercase letter and all other identifiers with a lowercase
letter.
Starting an identifier with a single leading underscore indicates by convention that the
identifier is meant to be private.
Starting an identifier with two leading underscores indicates a strongly private
identifier.
If the identifier also ends with two trailing underscores, the identifier is a languagedefined special name.
Reserved Words:
The following list shows the reserved words in Python. These reserved words may not
be used as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
And
Break
continue
Del
Else

exec
for
global
import
is

not
pass
Raise
try
with

assert
class
def
elif
except

finally
from
if
in
lambda

or
print
return
while
yield

6 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Python Variables and Data types
Variables are nothing but reserved memory locations to store values. This means that
when we create a variable we reserve some space in memory.
Assigning Values to Variables
Python variables do not have to be explicitly declared a data type to store the values.
The declaration happens automatically when we assign a value to a variable. The equal sign
(=) is used to assign values to variables.
For example:
counter = 100
# An integer assignment
miles = 1000.0
# A floating point
name = "John"
# A string
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles and name variables,
respectively. While running this program, this will produce the following result:
100
1000.0
John
Standard Data Types
The data stored in memory can be of many types. Python has various standard 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. They are an immutable data type which
means that changing the value of a number data type results in a newly allocated object.
Number objects are created when we assign a value to them.

7 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


For example:
var1 = 1
var2 = 10
We 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]]]]
Python supports four different numerical types:
int (signed integers)
long (long integers [can also be represented in octal and hexadecimal])
float (floating point real values)
complex (complex numbers)
Examples:
Here are some examples of numbers:
int
10
100
-786
-0490
-0x260

Long
51924361L
-0x19323L
0122L
535633629843L
-052318172735L

float
0.0
15.20
-21.9
-90.
-32.54e100

complex
3.14j
45.j
9.322e-36j
-.6545+0J
3e+26J

Python allows us to use a lowercase L with long, Python displays long integers with
an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by a + bj, where a is the real part and b is the imaginary part of the complex number.
Python Strings
Strings in Python are identified as a contiguous set of characters in between quotation
marks. Python allows for either pairs 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 -1 from the end of the string.
The plus ( + ) sign is the string concatenation operator and the asterisk ( * ) is the repetition
operator. For example:

str = 'Hello World!'


print str
# Prints complete string
print str[0]
# Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
8 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


print str[2:]
# Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
This will produce the following result:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.
For example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
print list
# Prints complete list
print list[0]
# Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:]
# Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
This will produce the following result:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

9 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists. For example:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print tuple
# Prints complete list
print tuple[0]
# Prints first element of the list
print tuple[1:3]
# Prints elements starting from 2nd till 3rd
print tuple[2:]
# Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
This will produce the following result:
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or
hashes and consist of key-value pairs. A dictionary key can be almost any Python type, but
are usually numbers or strings. Values can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and
accessed using square braces ( [] ). For example:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one']
# Prints value for 'one' key
print dict[2]
# Prints value for 2 key
print tinydict
# Prints complete dictionary
print tinydict.keys() # Prints all the keys
10 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


print tinydict.values() # Prints all the values
This will produce the following result:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Python Operators
Operator is a special type of symbol to indicate to the python interpreter to perform
specific type of operation. There are several categories of the operators in python.
Arithmetic Operators
Comparison (i.e., Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then:
Operator Description

Example

Addition - Adds values on either side of


a + b will give 30
the operator

Subtraction - Subtracts right hand


a - b will give -10
operand from left hand operand

Multiplication - Multiplies values on


a * b will give 200
either side of the operator

Division - Divides left hand operand by


b / a will give 2
right hand operand

Modulus - Divides left hand operand by


right hand operand and returns b % a will give 0
remainder

**

Exponent - Performs exponential


a**b will give 10 to the power 20
(power) calculation on operators

//

Floor Division - The division of


operands where the result is the quotient 9//2 is equal to 4 and 9.0//2.0 is equal to
in which the digits after the decimal 4.0
point are removed.

11 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Python Comparison Operators
Assume variable a holds 10 and variable b holds 20, then:
Operator Description
Example
Checks if the value of two operands is
==
equal or not, if yes then condition (a == b) is not true.
becomes true.
!=

Checks if the value of two operands are


equal or not, if values are not equal then (a != b) is true.
condition becomes true.

<>

Checks if the value of two operands are


(a <> b) is true. This is similar to !=
equal or not, if values are not equal then
operator.
condition becomes true.

>

Checks if the value of left operand is


greater than the value of right operand, (a > b) is not true.
if yes then condition becomes true.

<

Checks if the value of left operand is


less than the value of right operand, if (a < b) is true.
yes then condition becomes true.

>=

Checks if the value of left operand is


greater than or equal to the value of
(a >= b) is not true.
right operand, if yes then condition
becomes true.

<=

Checks if the value of left operand is


less than or equal to the value of right
(a <= b) is true.
operand, if yes then condition becomes
true.

Python Assignment Operators:


Assume variable a holds 10 and variable b holds 20, then:
Operator Description
Example
Simple assignment operator, Assigns
=
values from right side operands to left c = a + b will assigne value of a + b into c
side operand
+=

Add AND assignment operator, It adds


right operand to the left operand and c += a is equivalent to c = c + a
assign the result to left operand

-=

Subtract AND assignment operator, It


subtracts right operand from the left
c -= a is equivalent to c = c - a
operand and assign the result to left
operand

*=

Multiply AND assignment operator, It c *= a is equivalent to c = c * a


12 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


multiplies right operand with the left
operand and assign the result to left
operand
/=

Divide AND assignment operator, It


divides left operand with the right
c /= a is equivalent to c = c / a
operand and assign the result to left
operand

%=

Modulus AND assignment operator, It


takes modulus using two operands and c %= a is equivalent to c = c % a
assign the result to left operand

**=

Exponent AND assignment operator,


Performs
exponential
(power)
c **= a is equivalent to c = c ** a
calculation on operators and assign
value to the left operand

//=

Floor Dividion and assigns a value,


Performs floor division on operators c //= a is equivalent to c = c // a
and assign value to the left operand

Python Bitwise Operators:


Bitwise operator works on bits and performs bit by bit operation. There are following Bitwise
operators supported by Python language
Assume if a = 60; and b = 13;
Operator Description
Example
Binary AND Operator copies a bit to
&
(a & b) will give 12 which is 0000 1100
the result if it exists in both operands.
|

Binary OR Operator copies a bit if it


(a | b) will give 61 which is 0011 1101
exists in eather operand.

Binary XOR Operator copies the bit if it


(a ^ b) will give 49 which is 0011 0001
is set in one operand but not both.

(~a ) will give -61 which is 1100 0011 in


Binary Ones Complement Operator is
2's complement form due to a signed
unary and has the efect of 'flipping' bits.
binary number.

<<

Binary Left Shift Operator. The left


operands value is moved left by the
a << 2 will give 240 which is 1111 0000
number of bits specified by the right
operand.

>>

Binary Right Shift Operator. The left


operands value is moved right by the
a >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.

13 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Python Logical Operators
There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then:
Operator Description
Example
Called Logical AND operator. If both
and
the operands are true then then (a and b) is true.
condition becomes true.
or

Called Logical OR Operator. If any of


the two operands are non zero then then (a or b) is true.
condition becomes true.

not

Called Logical NOT Operator. Use to


reverses the logical state of its operand.
not(a and b) is false.
If a condition is true then Logical NOT
operator will make false.

Python Membership Operators


Python has membership operators, which test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators explained below:
Operator Description

Example

in

Evaluates to true if it finds a variable in


x in y, here in results in a 1 if x is a
the specified sequence and false
member of sequence y.
otherwise.

not in

Evaluates to true if it does not finds a


x not in y, here not in results in a 1 if x is
variable in the specified sequence and
not a member of sequence y.
false otherwise.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two
Identity operators explained below:
Operator Description
Example
Evaluates to true if the variables on
x is y, here is results in 1 if id(x) equals
is
either side of the operator point to the
id(y).
same object and false otherwise.
is not

Evaluates to false if the variables on


x is not y, here is not results in 1 if id(x)
either side of the operator point to the
is not equal to id(y).
same object and true otherwise.

14 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

Python Numbers
Number data types store numeric values. They are immutable data types, which
mean that changing the value of a number data type results in a newly allocated object.
Number objects are created when we assign a value to them. For example:
var1 = 1
var2 = 10
We 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]]]]
We 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): often called just integers or ints, are positive or negative whole
numbers with no decimal point.
long (long integers ): or longs, are integers of unlimited size, written like integers and
followed by an uppercase or lowercase L.
float (floating point real values) : or floats, 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 10 2 = 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). a is the real
part of the number, and b is the imaginary part. Complex numbers are not used much
in Python programming.
Examples:
Here are some examples of numbers:
int
10

long
51924361L

float complex
0.0 3.14j

100

-0x19323L

15.20 45.j

-786 0122L

-21.9 9.322e-36j

-0490 535633629843L -90.

-.6545+0J

15 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Operators
Numeric types support a wide variety of operators, ranging from the standard type of
operators to operators created specifically for numbers. Some of the operators are arithmetic
operators, relational operators, bitwise operators, logical operators, equality operators.
Example Arithmetic Operators
Operator Description
Example
Addition - Adds values on either side of
+
a + b will give 30
the operator
-

Subtraction - Subtracts right


operand from left hand operand

hand

Multiplication - Multiplies values on


a * b will give 200
either side of the operator

Division - Divides left hand operand by


b / a will give 2
right hand operand

Modulus - Divides left hand operand by


right hand operand and returns b % a will give 0
remainder

**

Exponent - Performs exponential


a**b will give 10 to the power 20
(power) calculation on operators

//

Floor Division - The division of


operands where the result is the quotient 9//2 is equal to 4 and 9.0//2.0 is equal to
in which the digits after the decimal 4.0
point are removed.

a - b will give -10

Built-in Functions on Numbers


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

16 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Mathematical Functions
Python includes following functions that perform mathematical calculations.
Function

Returns ( description )

abs(x)

The absolute value of x: the (positive) distance between x and zero.

ceil(x)

The ceiling of x: the smallest integer not less than x

cmp(x, y)

-1 if x < y, 0 if x == y, or 1 if x > y

floor(x)

The floor of x: the largest integer not greater than x

log(x)

The natural logarithm of x, for x> 0

max(x1, x2,...)

The largest of its arguments: the value closest to positive infinity

min(x1, x2,...)

The smallest of its arguments: the value closest to negative infinity

pow(x, y)

The value of x**y.

round(x [,n])

x rounded to n digits from the decimal point. Python rounds away


from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

sqrt(x)

The square root of x for x > 0

divmod(x)

The divmod() built-in function combines division and modulus


operations into a single
function call that returns the pair (quotient, remainder) as a tuple.

17 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

Python Objects
Python uses the object model abstraction for data storage. Any construct which
contains any type of value is an object. All Python objects have the three characteristics: an
identity, a type, and a value.
IDENTITY

TYPE

VALUE

Unique identifier that differentiates an object from all others. Any object's
identifier can be obtained using the id() built-in function. This value is very
similar to a "memory address" in Python
An object's type indicates what kind of values an object can hold, what
operations can be applied to such objects, and what behavioral rules these
objects are subject to. We can use the type() built-in function to reveal the
type of a Python object.
Data item that is represented by an object.

Standard and Built-in Types of Objects


Python supports a set of basic standard built-in data types, as well as some auxiliary
types. Most applications generally use the standard types.
Standard Types
Numbers
o Regular or "Plain" Integer
o Long Integer
o Floating Point Real Number
o Complex Number
String
List
Tuple
Dictionary
Built in Types
Type
None
File
Function
Module
Class
Class Instance
Method
Standard Type Operators
Value Comparison
Comparison operators are used to determine equality of two data values between
members of the same type. These comparison operators are supported for all built-in types.
Comparisons yield true or false values, based on the validity of the comparison expression.
18 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Python chooses to interpret these values as the plain integers 0 and 1 for false and true,
respectively.
Operator
expr1 < expr2
expr1 > expr2
expr1 <= expr2
expr1 >= expr2
expr1 == expr2
expr1 != expr2
expr1 <> expr2

Function
expr1 is less than expr2
expr1 is greater than expr2
expr1 is less than or equal to expr2
expr1 is greater than or equal to expr2
expr1 is equal to expr2
expr1 is not equal to expr2 (C-style)
expr1 is not equal to expr2

For example
>>> 2 == 2
1
>>> 2.46 <= 8.33
1
>>> 5+4j >= 2-3j
1
>>> 'abc' == 'xyz'
0
>>> 'abc' > 'xyz'
0
>>> [3, 'abc'] == ['abc', 3]
0
>>> [3, 'abc'] == [3, 'abc']
1
Boolean
Expressions may be linked together or negated using the Boolean logical operators
and, or, and not, all of which are Python keywords. These Boolean operations are in highestto-lowest order of precedence.
Operator
not expr
expr1 and expr2
expr1 or expr2
For example

function
logical NOT of expr (negation)
logical AND of expr1 and expr2 (conjunction)
logical OR of expr1 and expr2 (disjunction

>>> x, y = 3.1415926536, -1024


>>> x < 5.0
1
>>> not (x < 5.0)
0
>>> (x < 5.0) or (y > 2.718281828)
1
>>> (x < 5.0) and (y > 2.718281828)
0
>>> not (x is y)
1
19 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Object Identity Comparison
Python provides is and is not operators to test if a pair of variables do indeed refer to
the same object. Performing a check such as a is b is an equivalent expression to id(a) ==
id(b). The list of Object identity comparison operators are
operator
obj1 is obj2
obj1 is not obj2

function
obj1 is the same object as obj2
obj1 is not the same object as obj2

For example
>>> a = [ 5, 'hat', -9.3]
>>> b = a
>>> a is b
1
>>> a is not b
0
>>>
>>> b = 2.5e-5
>>> b
2.5e-005
>>> a
[5, 'hat', -9.3]
>>> a is b
0
>>> a is not b
1
Standard Type Built-in Functions
Python also provides some built in functions that can be applied to all the basic object
types. Those are cmp(), repr(), str(), type().
function
cmp(obj1, obj2)

repr(obj)/' obj
str(obj)
type(obj)

operation
compares obj1 and obj2, returns integer i where:
i < 0 if obj1 < obj2
i > 0 if obj1 > obj2
i == 0 if obj1 == obj2
returns evaluatable string representation of obj
returns printable string representation of obj
,determines type of obj and return type object

cmp()
The cmp() built-in function CoMPares two objects, say, obj1 and obj2, and returns a
negative number (integer) if obj1 is less than obj2, a positive number if obj1 is greater
than obj2, and zero if obj1 is equal to obj2.
For example
20 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


>>> a, b = -4, 12
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = -4
>>> cmp(a,b)
0
>>>
>>> a, b = 'abc', 'xyz'
>>> cmp(a,b)
-23
>>> cmp(b,a)
23
>>> b = 'abc'
>>> cmp(a,b)
0
str() and repr()
The str() STRing and repr() REPResentation built-in functions or the single back or
reverse quote operator ( `` ) is used either to recreate an object through evaluation or obtain a
human-readable view of the contents of objects, data values, object types, etc. To use these
operations, a Python object is provided as an argument and some type of string representation
of that object is returned.
For example
>>> str(4.53-2j)
'(4.53-2j)'
>>>
>>> str(1)
'1'
>>>>>> str(2e10)
'20000000000.0'
>>>
>>> str([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> repr([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> `[0, 5, 9, 9]`
'[0, 5, 9, 9]'
Type and the type() Built-in Function
The type() built-in function takes any object as an argument and returns its type. The
return object is a type object itself.
The syntax is as follows:

21 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


type(object)
For example
>>> type(4) #int type
<type 'int'>
>>>
>>> type('Hello World!') #string type
<type 'string'>
>>>
>>> type(type(4)) #type type
<type 'type'>

Python Decision Making Statements (Conditionals and Loops)


Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or statements to
be executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Python programming language assumes any non-zero and non-null values as true,
and if it is either zero or null, then it is assumed as false value.
Python programming language provides following types of decision making statements.
Statement
if statements
if...else statements
nested if statements

Description
An if statement consists of a Boolean expression followed by one or
more statements.
An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
We can use one if or else if statement inside another if or else if
statement(s).

If Statement
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
The syntax of an if statement in Python programming language is:
if expression:
statement(s)
22 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


If the Boolean expression evaluates to true, then the block of statement(s) inside the
if statement will be executed. If Boolean expression evaluates to false, then the first set of
code after the end of the if statement(s) will be executed.
Flow Diagram:

Example:

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!"
When the above code is executed, it produces the following result:
1 - Got a true expression value
100
Good bye!

23 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


If - else statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement resolves to 0
or a false value.
The else statement is an optional statement and there could be at 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/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
24 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
When the above code is executed, it produces the following result:
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!

The elif Statement


The elif statement allows us to check multiple expressions for truth value and execute
a block of code as soon as one of the conditions evaluates to true. There can be an arbitrary
number of elif statements following an if.
The syntax of the if...elif statement is:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example:

var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
25 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


else:
print "4 - Got a false expression value"
print var
print "Good bye!"
When the above code is executed, it produces the following result:
3 - Got a true expression value
100
Good bye!
.
Nested if Statements
There may be a situation when we want to check for another condition after a
condition resolves to true. In such a situation, we can use the nested if construct.
In a nested if construct, we 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:

var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
26 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
print "Good bye!"
When the above code is executed, it produces following result:
Expression value is less than 200
Which is 100
Good bye!
Looping Statements
There may be a situation when we need to execute a block of code several number of
times. A loop statement allows us to execute a statement or group of statements multiple
times. Python programming language provides following types of loops to handle looping
requirements.
Loop Type
while loop
for loop
nested loops

Description
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
We can use one or more loop inside any another while, for or do..while loop.

while loop
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
The syntax of a while loop in Python programming language is:
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition
may be any expression, and true is any non-zero value. The loop iterates while the condition
is true.
When the condition becomes false, program control passes to the line immediately following
the loop.

27 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Flow Diagram:

Example:

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:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

28 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


for loop
The for loop in Python has the ability to iterate over the items of any sequence, such
as a list or a string.
Syntax:
The syntax of a for loop look is as follows:
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.
Flow Diagram:

Example:

for letter in 'Python': # First Example


print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
# Second Example
print 'Current fruit :', fruit
29 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


When the above code is executed, it produces the following result:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Nested Loops
Python programming language allows using one loop inside another loop.
Syntax:
The syntax for a nested for loop statement in Python is as follows:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#!/usr/bin/python
i=2
while(i < 50):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
print "Good bye!"
30 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


When the above code is executed, it produces following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
Good bye!

The else Statement Used with Loops


Python supports to have an else statement associated with a loop statement.
If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
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 else statement gets
executed.
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"

31 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

Python Sequences
The most basic data structure in Python is the sequence. Sequences allow us to store
multiple values in an organized and efficient fashion. Each element of a sequence is assigned
a number - its position or index. There are five kinds of sequences in Python: strings, lists,
tuples, dictionaries, and sets.
There are certain things we can do with all sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has
built-in functions for finding the length of a sequence and for finding its largest and smallest
elements.
Sequence Elements storage and Access Model

Operators
Sequence objects allow applying the operators directly on its elements. The
functionality of the operators is same on all sequence type objects. Some of the operators are

Built-in Functions
There are the categories of built-in functions that could manipulate the elements of
Sequence objects directly.

32 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Conversion Functions
The list(), str(), and tuple() built-in functions are used to convert from any sequence
type to another.

Operational Functions
Python provides the following operational built-in functions for sequence types.

Strings
Strings are the most popular sequence types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes and double quotes as same.
Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings:
To access substrings, we can use the square brackets for slicing along with the index
or indices to obtain our desired substring. Following is a simple example:
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result:
var1[0]: H
var2[1:5]: ytho
33 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Updating Strings
We can "update" an existing string by reassigning a variable to another string. The
new value can be related to its previous value or to a completely different string altogether.
Following is a simple example:

var1 = 'Hello World!'


print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result:
Updated String :- Hello Python
String Operators
All Standard type operators and sequence type operators can be applied to strings.
The following are the operators applied on Strings.
Operator Description

Example ( a =Hello , b=Python )

Concatenation - Adds values on either


a + b will give HelloPython
side of the operator

Repetition - Creates new strings,


concatenating multiple copies of the a*2 will give -HelloHello
same string

[]

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


given index
b[-2] will give o

[:]

Range Slice - Gives the characters


a[1:4] will give ell
from the given range

in

Membership - Returns true if a


H in a will give 1
character exists in the given string

not in

Membership - Returns true if a


character does not exist in the given M not in a will give 1
string

Built-in Functions
Standard Type Functions
cmp()
As with the value comparison operators, the cmp() built-in function also performs a
Lexicographic comparison for strings.
>>> str1 = 'abc'
>>> str2 = 'lmn'
>>> str3 = 'xyz'
34 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


>>> cmp(str1, str2)
-11
>>> cmp(str3, str1)
23
>>> cmp(str2, 'lmn')
0
Sequence Type Functions
len()
The len() built-in function returns the number of characters in the string as expected.
>>> str1 = 'abc'
>>> len(str1)
3
>>> len('Hello World!')
12
The len() built-in function returns the number of characters in the string as expected.
max() and min()
The max() and min() built-in functions will return the greatest and least characters
respectively.
>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> max(str2)
'n'
>>> min(str3)
'x'
String Built-in Methods
String methods are intended to replace most of the functionality in the string module
as well as to bring new functionality to the string object.
String Method Name
string.capitalize()
string.count(str, beg= 0,end=len(string))

string.endswith(str, beg=0,
end=len(string))
string.find(str, beg=0 end=len(string))

Description
capitalizes first letter of string
counts how many times str occurs in string,
or in a substring of string if starting index
beg and ending index end are given
determines if string or a substring of string
ends with str returns 1 if so, and 0
otherwise
determine if str occurs in string, or in a
substring of string if starting index beg and
ending index end are given returns index if

35 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


found and -1 otherwise
same as find(), but raises an exception if str
not found
string.isalpha()
returns 1 if string has at least 1 character
and all characters are alphabetic and 0
otherwise
string.isdigit()
returns 1 if string contains only digits and 0
otherwise
string.islower()
returns 1 if string has at least 1 cased
character and all cased characters are in
lowercase and 0 otherwise
string.isupper()
returns 1 if string has at least one cased
character and all cased characters are in
uppercase and 0 otherwise
string.lower()
converts all uppercase letters in string to
lowercase
string.upper()
converts lowercase letters in string to
uppercase
string.replace(str1,
replaces all occurrences of str1 in string
str2,num=string.count(str1))
with str2, or at most num occurrences if
num given
string.startswith(str,beg=0,end=len(string)) determines if string or a substring of string
starts with substring str returns 1 if so, and
0 otherwise
string.index(str, beg=0, end=len(string))

Python Lists
The list is a most versatile data type available in Python which can be written as a list
of comma-separated values (items) between square brackets. The items in a list need not all
have the same type.
Creating a list is as simple as putting different comma-separated values between
square brackets ( [ ] ). Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on. For example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. Following is a simple example:

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];
36 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT

print "list1[0]: ", list1[0]


print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
We can update single or multiple elements of lists by giving the slice on the left-hand
side of the assignment operator, and we can also add to elements in a list with the append()
method. Following is a simple example:

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2];
list[2] = 2001;
print "New value available at index 2 : "
print list[2];

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


Value available at index 2 :
1997
New value available at index 2 :
2001
Deleting List Elements
To remove a list element, we can use either the del statement if we know exactly
which element we are deleting. Following is a simple example:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
When the above code is executed, it produces following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
37 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Basic List Operators
We can apply all standard type operators and sequence type operators to the lists.
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string. For example
Python Expression
len([1, 2, 3])

Results
3

Description
Length

[1, 2, 3] + [4, 5, 6]

[1, 2, 3, 4, 5, 6]

Concatenation

['Hi!'] * 4

['Hi!', 'Hi!', 'Hi!', 'Hi!']

Repetition

3 in [1, 2, 3]

True

Membership

for x in [1, 2, 3]: print x, 1 2 3

Iteration

Indexing and Slicing


Because lists are sequences, indexing and slicing work the same way for lists as they
do for strings.
Assuming following input, some of the python expressions are
L = ['spam', 'Spam', 'SPAM!']

Python Expression

Results

Description

L[2]

'SPAM!'

Offsets start at zero

L[-2]

'Spam'

Negative: count from the right

L[1:]

['Spam', 'SPAM!']

Slicing fetches sections

Built in List Function


cmp(list1, list2)
The method cmp() compares elements of two lists.
Syntax
Following is the syntax for cmp() method:
cmp(list1, list2)
Parameters
list1 -- This is the first list to be compared.
list2 -- This is the second list to be compared.
38 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Return Value
If elements are of the same type, perform the compare and return the result. If elements
are different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary and compare.
If either element is a number, then the other element is "larger" (numbers are
"smallest").
Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists
and share the same data, the result is a tie, meaning that 0 is returned.
Example
The following example shows the usage of cmp() method.

list1, list2 = [123, 'xyz'], [456, 'abc']


print cmp(list1, list2);
print cmp(list2, list1);
list3 = list2 + [786];
print cmp(list2, list3)
This will produce the following result:
-1
1
-1
len(list)
The method len() returns the number of elements in the list.
Syntax
Following is the syntax for len() method:
len(list)
Parameters
list -- This is a list for which number of elements to be counted.
Return Value
This method returns the number of elements in the list.
Example
39 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


The following example shows the usage of len() method.

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']


print "First list length : ", len(list1);
print "Second list length : ", len(list2);
This will produce the following result:
First list length : 3
Second lsit length : 2
max(list)
The method max returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method:
max(list)
Parameters
list -- This is a list from which max valued element to be returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]


print "Max value element : ", max(list1);
print "Max value element : ", max(list2);
This will produce the following result:
Max value element : zara
Max value element : 700

40 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


min(list)
The method min() returns the elements from the list with minimum value.
Syntax
Following is the syntax for min() method:
min(list)
Parameters
list -- This is a list from which min valued element to be returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]


print "min value element : ", min(list1);
print "min value element : ", min(list2);
this will produce the following result:
min value element : 123
min value element : 200
List Methods
SN Methods with Description
1

list.append(obj) : Appends object obj to list

list.count(obj) : Returns count of how many times obj occurs in list

list.extend(seq) : Appends the contents of seq to list

list.index(obj) : Returns the lowest index in list that obj appears

list.insert(index, obj) : Inserts object obj into list at offset index

41 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


6

list.pop(obj=list[-1]) : Removes and returns last object or obj from list

list.remove(obj) : Removes object obj from list

list.reverse() : Reverses objects of list in place

list.sort([func]) : Sorts objects of list, use compare func if given

Tuples
A Tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The only difference is that tuples can't be changed i.e., tuples are immutable and tuples
use parentheses and lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values and
optionally we can put these comma-separated values between parentheses also. Like string
indices, tuple indices starts at 0, and tuples can be sliced, concatenated and so on. For
example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing:
tup1 = ( );
To write a tuple containing a single value you have to include a comma, even though
there is only one value:
tup1 = (50,);
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. Following is a simple example:

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
When the above code is executed, it produces the following result:
tup1[0]: physics
42 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
Tuples are immutable which means you cannot update them or change values of tuple
elements. But we able to take portions of an existing tuples to create a new tuples as follow.
Following is a simple example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result:
(12, 34.56, 'abc', 'xyz')
Basic Tuple Operators
All types of operators cannot be applied to tuples as they are immutable itself. We
can apply len( ), in and not in operators to the tuples. For example
Python Expression

Results

Description

len((1, 2, 3))

Length

3 in (1, 2, 3)

True

Membership

for x in (1, 2, 3): print


123
x,

Iteration

Indexing and Slicing


Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input:
L = ('spam', 'Spam', 'SPAM!')
Python Expression

Results

Description

L[2]

'SPAM!'

Offsets start at zero

L[-2]

'Spam'

Negative: count from the


right

L[1:]

['Spam', 'SPAM!']

Slicing fetches sections

43 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


Built-in Tuple Functions
Python includes the following tuple functions:
SN Function with Description
1

cmp(tuple1, tuple2) :Compares elements of both tuples.

len(tuple) : Gives the total length of the tuple.

max(tuple) : Returns item from the tuple with max value.

min(tuple) : Returns item from the tuple with min value.

tuple(seq) : Converts a list into tuple.

Dictionaries
A dictionary is mutable and is another container type that can store any number of
Python objects. Dictionaries consist of pairs of keys and their corresponding values. Python
dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without any
items is written with just two curly braces ( { } ). Keys are unique within a dictionary while
values may not be. The values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, we can use the square brackets along with the key to
obtain its value. Following is a simple example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
When the above code is executed, it produces the following result:
dict['Name']: Zara
dict['Age']: 7
44 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


If we attempt to access a data item with a key, which is not part of the dictionary, we
get an error as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
When the above code is executed, it produces the following result:
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary
We can update a dictionary by adding a new entry or item (i.e., a key-value pair),
modifying an existing entry, or deleting an existing entry as shown below in the simple
example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age'];


print "dict['School']: ", dict['School'];
When the above code is executed, it produces the following result:
dict['Age']: 8
dict['School']: DPS School
Deleting Dictionary Elements
We can either remove individual dictionary elements or clear the entire contents of a
dictionary. We can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
45 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - VI IV IT


del dict ;

# delete entire dictionary

print "dict['Age']: ", dict['Age'];


print "dict['School']: ", dict['School'];
This will produce the following result. Exception is raised; this is because after del dict
dictionary does not exist anymore:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Built-in Dictionary Functions & Methods
Python includes the following dictionary functions:
SN Function with Description
1

cmp(dict1, dict2) : Compares elements of both dict.

len(dict) : Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.

str(dict) : Produces a printable string representation of a dictionary

Python includes following dictionary methods


SN Methods with Description
1

dict.clear() : Removes all elements of dictionary dict

dict.get(key) : For key key, returns value or default if key not in dictionary

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

dict.items() : Returns a list of dict's (key, value) as tuple pairs

dict.keys() : Returns list of dictionary dict's keys

dict.values() : Returns list of dictionary dict's values

46 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

You might also like