Python Demo

You might also like

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

- Pure Object oriented programming language

- Vamsi singuluri
1. Python is an easy to learn, powerful programming language. It has
efficient high-level data structures and a simple but effective approach
to object-oriented programming.

2. Python’s elegant syntax and dynamic typing, together with its


interpreted nature, make it an ideal language for scripting and rapid
application development in many areas on most platforms.

3. The Python interpreter is easily extended with new functions and data
types implemented in C or C++ (or other languages callable from C).
Python is also suitable as an extension language for customizable
applications.

4. Python is simple to use, but it is a real programming language, offering


much more structure and support for large programs than shell scripts
or batch files can offer.
On the other hand, Python also offers much more error checking than
C, and, being a very-high-level language, it has high-level data types
built in, such as flexible arrays and dictionaries.
Python :

1. Python is an interpreted language, which can save you considerable


time during program development because no compilation and linking is
necessary. The interpreter can be used interactively, which makes it easy
to experiment with features of the language.

2. Python enables programs to be written compactly and readably.


Programs written in Python are typically much shorter than equivalent C,
C++, or Java programs, for several reasons:

a. The high-level data types allow you to express complex operations in a


single statement;

b. statement grouping is done by indentation instead of beginning and


ending brackets.

c. no variable or argument declarations are necessary.


INTRODUCTION:

1. Python is a general-purpose interpreted, interactive, object-oriented and


high-level programming language.

2. Python was created by Guido van Rossum in the late eighties and early
nineties.

3. Like Perl, Python source code is also now available under the GNU General
Public License.

4. Python is flexible scripting language.

POWERS OF PYTHON :

MAC, WINDOWS, LINUX, Maya, Game development, script mundane tasks.


Python is High –level , Interpreted , Interactive , OOPS.

 Designed to be Highly readable uses English Keywords

Interpreted: Processed at run time by the Interpreter. No need to compile your


program before executing it. Similar to Pearl and PHP.

Interactive: user can sit python prompt and Interact with Interpreter directly to
write
Your program.

Object-Oriented : Python supports Object –Oriented style or techniques of


programming that enacapsulate code in Objetcs.

Python is beginners language: Python is a great language for the beginners


programmers and supports the development of a wide range of applications from
simple text processing to www browsers to games.
History:

 Developed by Guido Van Rassum

 At research Institute for Mathematical and computer science in


Netherlands.

 Python is derived from many other languages, Including ABC, Modula-3,


C,C++, Algol-68, small talk, unix shell.

 Python is copyright.
FEATURES OF PYTHON:

1. Easy to learn : Python has relatively few key words, simple structure, clearly
defined syntax.
2. Easy to read: Python code is much more clearly defined.
3. Easy-to -maintain: Python success is that its source code is failrly easy-to
maintain.
4. A braod standard library: one of Python greatest strenght is the bulk of the
library is very Portable and cross plalform compatible on unix, windows.
5. Interactive Mode: Support for an Interactive mode in which you can enter
results From a terminal right to language, allow Interactive testing and
debugging of snippet.
6. Portable: python can run on a wide variety of Hardware Platform and has some
Interface on all platform.
7. Extendable:add low-level modules to Interpreter.
8. Database: provides Interface to all major commercial database.
9. GUI Programming: support GUI applicationcan be created and ported to many
system calls, libraries and windows systems.
10. Scalable: Python provide better structure and support for large programs than
shell scripting.
Installation :

Unix/Linux:

Open browser http://www.pythonorg/download

Step 1: Download and extract files.

Step 2: run ./configure script

Install in standard location /usr/local/bin and its libraries in


/usr/local/lib/pythonXXXX

Windows:

Download .exe file directly and Install directly.


Setting Environment path in Unix/Linux:

In general programs and other executable files can live in many directories
So OS provides a search path that list the directories.

The path variable is named PATH in Unix or Path in Windows.

In bash shell :

Export PATH = “$PATH: /usr/local/bin/python”

Windows:

At the command prompt : type

Path % path %; c:\python


Or
User can use graphical operation , by changing environment variables.
Running Python:

There are three different ways to start Python:

(1) Interactive Interpreter: You can enter python and start coding right away in the
interactive interpreter by starting it from the command line.

$python # Unix/Linux (or) C:>python # Windows/DOS

2) Script from the Command-line: A Python script can be executed at command


line by invoking the interpreter on your application, as in the following.

$python script.py (or) C:>python script.py

(3) Integrated Development Environment: You can run Python from a graphical
user interface (GUI) environment as well.

Unix: IDLE is the very first Unix IDE for Python.


Windows: PythonWin is the first Windows interface for Python and is an IDE with a
GUI.
First Python program:

Interactive Mode Programming:

Invoking the interpreter without passing a script file as a parameter brings up the
following prompt:
$ python Python 2.4.3 (#1, Nov 11 2010, 13:34:43) [GCC 4.1.2 20080704 (Red Hat 4.1.2-
48)] on linux2 Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, Python!";
Hello, Python!

Script Mode Programming:

Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished.
All python files will have extension test.py.

$ python test.py
Hello, Python!
Python Identifiers:

 used to identify a variable, class , module.

 Does not allow punctuation , characters such as @, $, and %.

 Allow letter A to Z or a to z and _ (underscore)

Naming convention in Python:

 class name starts with uppercase letter and all other Identifiers with lower
case.

 Starting Identifier with leading underscore by convenction , Identifier is


meant to be private.

 Starting an identifier with two leading underscores indicates a strongly


private identifier.
Lines and Indentation:

Python is the fact that there are no 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. Both blocks in this example are fine:
if True:
print "True“
else:
print "False"

Multi-Line Statements:

Statements in Python typically end with a new line. Python does,


however, allow the use of the line continuation character (\) to
denote that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Quotation in Python:

A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the physical line end are part of the comment and the
Python interpreter ignores them.

# First comment
print "Hello, Python!"; # second comment

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:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Waiting for the User:

The following line of the program displays the prompt, Press the enter key to
exit and waits for the user to press the Enter key:
>>> str = raw_input("Enter your input: ")
Enter your input: Hello Python
>>> str = input("Enter your input: ")

Difference between raw_input and Input:

Input The input([prompt]) function is equivalent to raw_input, except that it


assumes the input is a valid Python expression and returns the evaluated result
to you as interger.

raw_input: The raw_input([prompt]) function reads one line from standard


input and returns it as a string (removing the trailing newline).

>>> input() >>>raw_input()


3 --- integer ‘3’ -- string
Variables:

In general , Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in 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 variables, you can store integers, decimals or characters in these variables.

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

In Python variables are like Labels/Tags in which they refer to an object.

a = 10 [ All variables are references. Here a does not store values )

 Variables are like labels/tags used to refer to an object.


 Object have types , where as variables do not have types.
 All Identifiers In python are varibles.
All Identifiers in Python are variables:

Identifiers -- class name, function, constant, variables.

>>> def greet(): print "hello world!"

>>> greet() >>> greet


hello world! <function greet at 0x01D44FB0>

>>> a = greet

>>> a >>> a()


<function greet at 0x01D44FB0> hello world!

>>> type(greet) >>> type(a)


<type 'function‘> <type 'function'>

So , variables refer to an Object, function itself is an object.In python any thing and
every thing refers to an object. Objects are of two types

1. Mutable 2. Immutable
Assigning Values to Variables:

>>> a = 10
>>> print a >>> a >>> type(a)
10 10 <type 'int'>

How to pack and unpack values in tuple:


>>> a = 10,20,30
>>> b,c,d = a
>>> b >>> c >>> d
10 20 30

This is Implicit feature of Python :

To swap two varibales :


a = 10 , b= 20

>>> a, b = b,a
>>> a >>>b
20 10
String format operator:

>>> output = "name: %s, age: %s“


>>> rec = "john", 40
>>> output % rec
'name: john, age: 40‘
>>> output = "name:{NAME}, age : {AGE}“
>>> print output.format(NAME="sai", AGE = 34)
name:sai, age : 34

>>> html = """


<html>
<body>
<h1> {HEADER} </h1>
<p> message :{MESSAGE}
<\p>
<h2> time:{TIME} <\h4>
<\body>
<\html>
"""
>>> print html.format(HEADER = "A sample", MESSAGE = "Test message", TIME =
ctime())
Importance of Python:

 Python is Heavily Introspective language.

 Introspective - checking capability of an object.

 The first Introprective is Type of varibale

>>> a = 10
>>> type(a)
<type 'int'>

>>> a= 10,20,30
>>> type(a)
<type 'tuple'>

>>> a = {"name":"vamsi", "city": "hyd", "Id":345666}


>>> type(a)
<type 'dict'>
Python dynamic typing:

>>> a = 100
>>> b = a
Here only one Instance 100 , but a,b variables points to it.All objects in memory are
Unique. Every object having unique Id.

>>> a = 100 >>> b = 200


>>> id(a) >>> id(b)
19523572 19524356
Here, Id are different beacause variables are referenced to different object.

>>> a = 100 >>> b = a


19523572 19523572
Here , Id are same because varaibles referenced to same object 100.

Sometimes, values are same but Id are different as below :

>>> a = 1234567 >>> b = 1234567


>>> id(a) >>> id(b)
22367876 30264936
Capability of Python:

What could be reason behind Id are different for same Object???


Python decides to create an Object in run time, before creating an
Object It will check whether this obejct is there already.

Example : a = 10

First check object 10 is already existed.It will check based on compute hash
code of 10 and check with hash team if any one existed with same hash code.
But , hash code computation becomes more complicated with larger
values.So for larger values due to heavy computation, It will create new object
Id for variables.

In Example of string :
>>> a = "hello“ >>> b = "he llo“
>>> id(a) >>> id(b)
30612576 30824704

Here, white space in string consideres as paragraph/non-alphabet by python.


It will create new object Id due to high hash code computation.
Python Rule:

>>> def greet(): print "hello world“

>>> greet() >>> a = greet()


hello world hello world

>>> type(a) >>> print a


<type 'NoneType'> None

In python , all right side expression must return an object If they don’t return an
object , python Interpreter will return the left side with None

None is an object type.

>>> a is None
True
How .py are Interpreted by Python:

Step 1: when ever .py are executed.

There are two phases:

1. Checking for syntax of file [syntax parsing]


2. Byte compiled( create byte code)

After these two phases , Byte code loaded into memory and exeucted.

Python is byte compiled Interpreter language. Most of modern interpreters for


Performance reason they use byte code comparision.

Python has simplistic VM(Virtual machine) - this will take care to convert
source code to byte code.
After executing file .pyc files are generated in directory.
. .pyc are byte compiled code, and also user can use those to execute
program. So that program can skip syntax and byte code phases to increase
efficiency and execution speed of program.
What exactly Python Virtual Machine does?

 Python has a compiler! You just don't notice it because it runs


automatically. You can tell it's there, though: look at the .pyc files that are
generated for modules that you import. It does not compile to the native
machine's code. Instead, it compiles to a byte code that is used by a virtual
machine.

 The virtual machine is itself a compiled program. very similar to how Java
works; so similar, in fact, that there is a Python variant (Jython) that
compiles to the Java Virtual Machine's byte code instead! There's also
IronPython, which compiles to Microsoft's CLR (used by .NET)

 Jython (the system formerly known as JPython) is a Python implementation


forJava, which compiles Python source code to Java bytecode, and gives
Python scripts seamless access to Java class libraries on the local machine.
How do I create static class data and static class methods?

For static data, simply define a class attribute. To assign a new value to the
attribute, you have to explicitly use the class name in the assignment:

class C:
count = 0 # number of times C.__init__ called

def __init__(self):
C.count = C.count + 1

def getcount(self):
return C.count # or return self.count
SubProcess:
from subprocess import Popen , PIPE
from time import sleep
p = Popen(args="notepad")
sleep(5)
print "Terminating notepad"
p.kill()

 PIPE is used to read the standard output of child process to stdout where we
want too read output

Here using subprocess, python will perfom action of opening notepad and staying
Live within timeperiod it has mentioned and exit the action item.

.pyc files are python files compiled to byte code by the interpreter. They are
generated normally when a file is imported.
.pyo are compiled byte code without line numbers, assertions, and some other
things (possibly doc strings) for optimzation purposes.
when invoking the python interpreter, you may pass the -O or -OO option to
generate a .pyo file. Using -O will throw out the line numbers, assertions, and
some debugging info. -OO will result in a .pyo file also stripped of docstrings.
Alternate way to create class in python:

>>> class Myclass(object):


pass
>>> dir()
['Myclass', '__builtins__', '__doc__', '__name__', '__package__']
>>> x = Myclass()
>>> x
<__main__.Myclass object at 0x01C6ED10>
>>> Myclass
<class '__main__.Myclass'>

Myclass = type(“Myclass", (object,),{"x":5})

type ---> (same name, different functionality)

object -----> base class

{"x":5} ----> functions and vars

Myclass ---> class name


Example:
Class Myclass(object):
def __init__(self):
self.x = 5

TypeClass = type("TypeClass", (object,),{"x":5})

m = Myclass()
t = TypeClass()

print t.x, m.x


5, 5
How to use .py files as modules:

Any file with .py extension is a module

Print “hello world”


Varaibale = “sri ram”

def greet() : print “Hello guys!” { save above file snippet with hello.py}

>>> import hello


hello world
>>> import hello
>>>
>>> hello.Varaibale
'sriram‘
>>> hello.greet()
Hello guys!

Here, once .py is loaded as module, on execution program defines some variables
and methods and those can be accessed by importing to interpreter.when .py is
imported it will load into memory.
When I edit an imported module and reimport it, the changes don't show up.
Why does this happen?

>>> import hello


hello world
>>> import hello
>>>

For reasons of efficiency as well as consistency, Python only reads the module file on
the first time a module is imported.If it didn't, in a program consisting of many
modules where each one imports the same basic module,the basic module would be
parsed and re-parsed many times. To force rereading of a changed module, do this:

Import modname
reload(modname)
Where is the math.py (socket.py, regex.py, etc.) source file?
There are (at least) three kinds of modules in Python:

1. modules written in Python (.py);


2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3. modules written in C and linked with the interpreter; to get a list of these, type:

>>>import sys
>>>print sys.builtin_module_names
Python Documentation:

“”” This module used to perform some mathematical operations.

Module 1 : perform addtion


Module 2 : perform square
“””
VERSION = 2.4.55
AUTHOR = vamsi krishna

def addtion(self, x, y):


“””Method used to perform addtion operation.”””
z=x+y
def square(self, x):
“Method to perform multipilcation operation.”””
z = x*x

- In Python , pydoc tool has provided. To make docs in file to be HTML


Copy file to some directory

$ pydoc -w ./ { ./ -- indicates current directory}


$ pydoc -p 8080 { pydoc server localhost :8080}
strings in python :

a = “Hello world”
>>> a.startswith("Hello") >>> a.endswith("world")
True True

Check word in sentence:


>>> a = “This is a test string”
>>> ‘test’ in a >>> a.index(“test”) >>>a[10:15]
True 10 ‘test’

In python strings are Immutable, cannot be changed. There are functions to do


operations on strings, but these will create new object.

>>> a. replace(“test”, “temp”) >>> b = a.replace(“test”, “temp”)


‘This is a temp string’
>>> a >>>b
‘This is a test string’ ‘This is a temp string’

>>> a.upper() >>> a.lower() >>> a.capitalize >>> a.title()


Data Types:

None Type -- None


Bool -- True/False

Numbers:
Int, long, float, complex

Collections:
All collection are Iterables

under iterable objects -- collections - sequences -- ordered collection of


items( indexed)

str , tuple, list --- mostly used sequences

unicode, bytearray

All sequences have common features like


 all sequences have length (len)
 all sequences are Indexing.
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 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 immutable data types which
means that changing the value of a number data type results in a newly allocated
object.

Example : var1 = 1

You can delete a single object or multiple objects by using the del statement.
>>>del var
>>>del var_a, var_b

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 long float complex
10 51924361 0.0 3.14j
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 working their way from -1 at the end.

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
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 ([]). To some extent, lists are
similar to arrays in C. One difference between them is that all the items belonging to a
list can be of different data type.
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 : ['abcd', 786, 2.23, 'john',70.2000000003]


print list[0] # Prints first element of the list: abcd
print list[1:3] # Prints elements starting from 2nd till 3rd : [786, 2.23]
print list[2:] # Prints elements starting from 3rd element: [2.23, 'john', 70.200000003]
print tinylist * 2 # Prints list two times : [123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists :
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
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:

Example:

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


tinytuple = (123, 'john')

print tuple # Prints complete list ('abcd', 786, 2.23, 'john', 70.200000000000003)
print tuple[0] # Prints first element of the list abcd
print tuple[1:3] # Prints elements starting from 2nd till 3rd (786, 2.23)
print tuple[2:] # Prints elements starting from 3rd element (2.23, 'john', 70.20000003)
print tinytuple * 2 # Prints list two times (123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated lists:
('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 found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object. Dictionaries have no concept of order among elements.
It is incorrect to say that the elements are "out of order"; they are simply unordered.
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 This is one


print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']
Data type conversion:

Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type name as a function.There are several
built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.

Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Python Basic Operators:

Python language supports the following types of operators:

 Arithmetic Operators

 Comparison (i.e., Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators
Python Arithmetic Operators:
Python Comparison Operators:
Python Assignment Operators:
Python Bitwise Operators:
Bitwise operator works on bits and perform 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
Python Logical Operators:

Python Membership Operators:

In addition to the operators discussed previously, Python has membership operators,


which test for membership in a sequence, such as strings, lists, or tuples.
Python Identity Operators:
Identity operators compare the memory locations of two objects.

Example:
>>> a = "hello world“
>>> b = "hello world“

>>> a == b
True

>>> id(a) >>> id(b)


29809792 29808224

>>> a is b >>> a is not b


False True
Python Operators Precedence:
Python Decision Making:

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.

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 elif statement inside another if or elif
statement(s).

Example:

var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!“

Value of expression is 100


Good bye!
Python Loops:
There may be a situation when you 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.

Loop Control Statements:


Loop control statements change execution from its normal sequence.When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Lists:
The most basic data structure in Python is the sequence. Python has six built-in
types of sequences. list is that items in a list need not all have the same type.

** There are certain things you 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.

Python Lists:

The list is a most versatile datatype available in Python.

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

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.
>>>print "list1[0]: ", list1[0]
list1[0]: physics
Updating Lists:
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with
the append() method.

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


>>> list[2] = 2001
>>> print list[2]
2001

Delete List Elements:


To remove a list element, you can use either the del statement if you know
exactly which element(s) you are deleting or the remove() method if you do not
know.

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


>>> del list1[2]
>>> list1
['physics', 'chemistry', 2000]
>>> del list1
Here list will be deleted.
Basic List Operations:

Indexing, Slicing, and Matrixes:


lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
>>>L = ['spam', 'Spam', 'SPAM!']
Built-in List Functions & Methods:

Example:
The method cmp() compares elements of two lists.

Ouput
Python provides some additional list methods:
Python 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. tuples can be sliced,
concatenated.

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


 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.
>>> tup1 = ('physics', 'chemistry', 1997, 2000)
>>>print "tup1[0]: ", tup1[0]
tup1[0]: physics
Updating Tuples:

Tuples are immutable which means you cannot update them or change values of
tuple elements.
>>> tup1 = (12, 34.56)
>>>tup2 = ('abc', 'xyz')
>>>tup3 = tup1 + tup2
>>> print tup3
(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements:

Removing individual tuple elements is not possible. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded.
>>>tup = ('physics', 'chemistry', 1997, 2000)

>>> del tup


>>> print tup
Traceback (most recent call last):
File "test.py", line 9, in <module> print tup;
NameError: name 'tup' is not defined
Basic Tuples Operations:

Indexing, Slicing, and Matrixes:


tuples are sequences, indexing and slicing work the same way for tuples as they
do for strings.
Built-in Tuple Functions:

Example :
output
Python Dictionary:
A dictionary is mutable and is another container type that can store any number of
Python objects, including other container types. Dictionaries consist of pairs (called
items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables.

>>>dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

 An empty dictionary without any items is written with just two curly braces,
like this: {}.
 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, you can use the familiar square brackets along with
the key to obtain its value.

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


>>> print "dict['Name']: ", dict['Name']
dict['Name']: Zara
Updating Dictionary:

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

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


>>> dict['Age'] = 8
>>> print "dict['Age']: ", dict['Age']
dict['Age']: 8

Delete Dictionary Elements:

You can either remove individual dictionary elements or clear the entire contents of
a dictionary. You can also delete entire dictionary in a single operation.

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


>>>del dict['Name']; # remove entry with key 'Name‘
>>> dict.clear(); # remove all entries in dict
>>>del dict ; # delete entire dictionary
Properties of Dictionary Keys:

Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the
keys.There are two important points to remember about dictionary keys:

1. More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last
assignment wins.
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
>>>print "dict['Name']: " dict['Name']
dict['Name']: Manni

2. Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
>>>dict = {['Name']: 'Zara', 'Age': 7};
>>>print "dict['Name']: ", dict['Name']
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
Built-in Dictionary Functions & Methods:

Example:
cmp(dict1, dict2)

output
Dictionary methods:
Python date and time:

A Python program can handle date & time in several ways. Python's time and
calendar modules help track dates and times.
>>>import time
>>>ticks = time.time()
>>>ticks
7186862.73399

 Getting format time

>>>localtime = time.asctime( time.localtime(time.time()) )


>>>localtime
Tue Jan 13 10:17:09 2009
>>>import calendar
>>>cal = calendar.month(2008, 1)
>>>localtime = time.localtime(time.time())
>>>print "Local current time :", localtime
Local current time : time.struct_time(tm_year=2013, tm_mon=7, tm_mday=17,
tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)
Python 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.

Defining a Function:
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:

def printme( str ):


"This prints a passed string into this function"
print str
return

Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.

>>>printme("I'm first call to user defined function!")


I'm first call to user defined function!
Pass by reference vs value
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.

Here, we are maintaining reference of the passed object and appending


values in the same object. So, this would produce the following result:
passed by reference:

There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.

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:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required arguments:
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.
printme()  TypeError: printme() takes exactly 1 argument (0 given)
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.
>>>printme( str = "My string")
My string
Note, here order of the parameter does not matter.

>>>printinfo( age=50, name="miki" )


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. Following example gives an idea on
default arguments, it would print default age if it is not passed:

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


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.
The general syntax for a function with non-keyword variable arguments is
this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring“
function_suite
return [expression]

 An asterisk (*) is placed before the variable name that will hold the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call.
>>> def sum_num(*args): >>> def sum_num(n, *args):
print args print "n is ", n
>>> sum_num(10,20,30) print "args is", args
(10, 20, 30) >>> sum_num(10,20,45)
n is 10
args is tuple which collects allisvariables
args (20, 45) in
one tuple.
>>> rec = "john", 33, "hyd", "IT“
>>> def add_record(name, age, city, dept):
print "adding name", name, "age", age, "city",city, "dept",dept
>>> add_record(*rec)
adding name john age 33 city hyd dept IT
>>> add_record(rec)
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
add_record(rec)
TypeError: add_record() takes exactly 4 arguments (1 given)

>>> rec = "sam", 33, "delhi“


>>> add_record(*(rec + ("IT")))
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
add_record(*(rec + ("IT"))
TypeError: can only concatenate tuple (not "str") to tuple

>>> add_record(*(rec + ("IT",)))


adding name sam age 33 city delhi dept IT
Passing arguments to functions:

Def function( nondefault, default, variables, keyword arguments):

In some of optional keyword arguments in python we can write these as:

>>>def add_rec(**kwargs):
print kwargs
>>>add_rec(city = “hyd”, dept = “IT”)
{‘city’ :“hyd”, “dept”: “IT”} -- output returns as dictionary
>>> def add_rec(name, age = 30, *args, **kwargs):
print “name”, name
print “Age” , age
print “args”, args
print “kwargs”, kwargs

>>>add_rec(“john”) >>>add_rec(“john”, 40) >>>add_rec(“john”, 40, city =“hyd”)


name = john name=john name = john
age = 30 age = 40 age = 40
args = () args = () args = ()
Kwargs = {} kwarsg = {} kwargs = {‘city’=‘hyd’}
Anonymous Functions:
Lambda :
You can use the lambda keyword to create small anonymous functions. These
functions are called anonymous because they are not declared in the standard
manner by using the def keyword.
 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 lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.

Syntax:
The syntax of lambda functions contains only a single statement, which is as
follows:
lambda [arg1 [,arg2,.....argn]]:expression

>>> square = lambda x: x*x >>>square(10)


100
map(), filter(), lambda, and list comprehensions provide compact, elegant, and
efficient ways to encode a few common idioms in programming.

map():
The map() function applies a function to every member of an iterable and returns the
result. Typically, one would use an anonymous inline function as defined by lambda,
but it is possible to use any function
>>> def square(x):
return x**2
>>> squares = map(square, range(10))
>>> print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
>>> lengths = map(len, names)
>>> print lengths
[4, 3, 3, 5, 6, 7, 4]

Using lambda and map together:


>>> squares = map(lambda x: x**2, range(10))
>>> print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81
filter():

Filter takes a function returning True or False and applies it to a sequence, returning a
list of only those members of the sequence for which the function returned True.

Lambda forms can also be used with the filter function; in fact, they can be used
anywhere a function is expected in Python. A lambda form that returns True when this
condition is met is lambda x: x > 5 and x < 50.

>>> squares = map(lambda x: x**2, range(10))


>>> special_squares = filter(lambda x: x > 5 and x < 50, squares)
>>> print special_squares
[9, 16, 25, 36, 49]

>>> names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']


>>> b_names = filter(lambda s: s.startswith('B'), names)
>>> print b_names
['Bob', 'Barbara']
List Comprehensions:
All examples can be achieved using a consistent, clean, and elegant syntax called
list comprehensions.

The simplest form of a list comprehension is


[ expression-involving-loop-variable for loop-variable in sequence ]

>>> squares = [ x**2 for x in range(10) ]


>>> print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Print the reverse of each name in the list of names:


>>> print [ name[::-1] for name in names ]
['ennA', 'ymA', 'boB', 'divaD', 'eirraC', 'arabraB', 'hcaZ']

 Note that complex expressions can be put in the slot for expression-involving-loop-
variable. For example, here we build up a list of names, first letters, and lengths for
each name in the list:
>>> print [ [name, name[0], len(name)] for name in names ]
[['Anne', 'A', 4], ['Amy', 'A', 3], ['Bob', 'B', 3], ['David', 'D', 5], ['Carrie', 'C', 6]]
Nested list comprehensions:

[ expression-involving-loop-variables for outer-loop-variable in outer-sequence


for inner-loop-variable in inner-sequence ]
This is equivalent to writing:
results = []
for outer_loop_variable in outer_sequence:
for inner_loop_variable in inner_sequence:
results.append( expression_involving_loop_variables )

>>> possible_choices = [ [drink,food] for drink in ['water', 'tea' ] for food in ['ham',
'eggs’]]
>>> print possible_choices
[['water', 'ham'], ['water', 'eggs'], ['tea', 'ham'], ['tea', 'eggs']

Filtered list comprehensions:

>>> special_squares = [ x**2 for x in range(10) if x**2 > 5 and x**2 < 50 ]
>>> print special_squares
[9, 16, 25, 36, 49]
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:
1. Global variables 2 . Local variables

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

The globals() and locals() functions can


be used to return the names in the
global and local namespaces
depending on the location from where
they are called. The return type of
both these functions is dictionary.
Python 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.

The import Statement:


You can use any Python source file as a module by executing an import statement in
some other Python source file. The import has the following syntax:
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.
import module1[, module2[,... moduleN]
>>> import support

The from...import Statement


Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax:
from modname import name1[, name2[, ... nameN]]
>>> from fib import fibonacci
The from...import * Statement:
It is also possible to import all names from a module into the current namespace by
using the following import statement:

>>>from modname import *


This provides an easy way to import all the items from a module into the current
namespace.

Locating Modules:

When you import a module, the Python interpreter searches for the module in the
following sequences:
 The current directory.
 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
 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
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 following line of
source code:
>>>def Pots():
print "I'm Pots Phone"
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory:
 Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to
put explicit import statements in __init__.py as follows:

from Pots import Pots


from Isdn import Isdn
from G3 import G3
After you've added these lines to __init__.py, you have all of these classes
available when you've imported the Phone package.
Python Files I/O:

Opening and Closing Files:


Python provides basic functions and methods necessary to manipulate files by
default. You can do your most of the file manipulation using a file object.

The open Function:


Before you can read or write a file, you have to open it using Python's built-in open()
function. This function creates a file object, which would be utilized to call other
support methods associated with it.
Syntax:
file object = open(file_name [, access_mode][, buffering])
file_name: The file_name argument is a string value that contains the name of the
file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given
below in the table. This is optional parameter and the default file access mode is
read (r).
buffering: If the buffering value is set to 0, no buffering will take place. If the
buffering value is 1, line buffering will be performed while accessing a file. If you
specify the buffering value as an integer greater than 1, then buffering action will be
performed with the indicated buffer size. If negative, the buffer size is the system
default(default behavior).
list of the different modes of opening a file:
file object attributes:

Once a file is opened and you have one file object, you can get various information
related to that file.
close() Method:

 The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.

 Python automatically closes a file when the reference object of a file is


reassigned to another file. It is a good practice to use the close() method to close
a file.
Syntax:
fileObject.close()

Example:

This would produce the following result:


Name of the file: foo.txt
Reading and Writing Files:
The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.

The write() Method:


The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
 The write() method does not add a newline character ('\n') to the end of the
string:

Syntax:
fileObject.write(string)
read() Method:
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data and not just text.
Syntax:
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it
tries to read as much as possible, maybe until the end of file.

Example:
File Positions:
 tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
 seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2 then
the end of the file would be taken as the reference position.
Renaming and Deleting Files:

>>>import os

rename() Method:
>>> os.rename( "test1.txt", "test2.txt" )

remove() Method:
>>> os.remove("text2.txt")

mkdir() Method:
>>>os.mkdir("test")

chdir() Method:
>>>os.chdir("newdir")

getcwd() Method:
>>> os.getcwd()

rmdir() Method:
>>> os.rmdir('dirname')
When ever existed files are opened with write mode all data in file is truncated.
>>> lines = (“This is line1\n this is line 2”)
>>>f = open(“a.txt”, “w”)
>>>f.writelines(lines)
Python automatically flushes the files when closing them. But you may want to flush
the data before closing any file.
>>>f.flush()
>>>f.close()
 To check whether file is closed/not
>>> f.closed
True

To copy file from source to destination: src = open(argv[1], “r”)


des = open(argv[2], “w”)
from sys import argv data = src.read()
If len(argv) < 3: des.write(data)
print “usage: python dest.py source.py src.close()
Open(argv[2], “w”).write(open(argv[1].read()) dst.close()
- Big problem in file operation is to forget to close the file. This can be resolved
by file descriptors are available in python.
- language should close file automatically , python provides

>>> with open(argv[1], “r”) as src, open(argv[2], “w”) as dst:


while True:
data = src.read(BLOCL_SIZE)
if not data : break
dst.write(data)

>>>To check file cursor where location is :


>>>f = open(“a.txt”)
>>>f.readline() >>>f.readline() >>>f.tell()
‘This is 1st line’ ‘This is 2nd line’ 55

>>>f.seek(0) 0 --- begining of file


>>>f.seek(20,0)
>>>f.tell()
20
>>>f.seek(-10,1) -- 10 characters backward
Python Exceptions Handling:

Exception Handling: This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
Assertions: This would be covered in Assertions in Python tutorial.

What is Exception?
An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it can't cope with, it raises an exception. An
exception is a Python object that represents an error.

Handling an exception:
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Exception Syntax:

Example:
try-finally clause:

Example:

When an exception is thrown in the try block, the execution immediately passes
to the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the except statements if present in the
next higher layer of the try-except statement.

You might also like