Oss Unit-6 PDF
Oss Unit-6 PDF
Oss Unit-6 PDF
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.
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.
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
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.
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
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:
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
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
**
//
<>
>
<
>=
<=
-=
*=
%=
**=
//=
<<
>>
not
Example
in
not in
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
-.6545+0J
hand
**
//
Returns ( description )
abs(x)
ceil(x)
cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
floor(x)
log(x)
max(x1, x2,...)
min(x1, x2,...)
pow(x, y)
round(x [,n])
sqrt(x)
divmod(x)
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.
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
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
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
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!
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
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!
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
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
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.
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!
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:
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.
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
[]
[:]
in
not in
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
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
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:
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:
Results
3
Description
Length
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
Concatenation
['Hi!'] * 4
Repetition
3 in [1, 2, 3]
True
Membership
Iteration
Python Expression
Results
Description
L[2]
'SPAM!'
L[-2]
'Spam'
L[1:]
['Spam', 'SPAM!']
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:
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
Iteration
Results
Description
L[2]
'SPAM!'
L[-2]
'Spam'
L[1:]
['Spam', 'SPAM!']
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
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:
len(dict) : Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
dict.get(key) : For key key, returns value or default if key not in dictionary