Sunday, 2 August 2015

Let's do some tuple operations

Tuples:


A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −
tup1 = ('pen', 'pencil', 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,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

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. For example −
#!/usr/bin/python

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
tup2[1:5]:  [2, 3, 4, 5]

Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates 

#!/usr/bin/python

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')

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.
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python

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

print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is because after del tuptuple does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print tup;
NameError: name 'tup' is not defined



Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −

1)Length

     Eg: len((1, 2, 3))   =3

2)Concat

     Eg: (1.2,3) + (4,5,6) = (1, 2, 3, 4, 5, 6)


3)Repetition 

   Eg:('Hi',) * 2  = ('Hi','Hi')  

4)Membership

  Eg:3 in (1, 2, 3) = True

5)Iteration

  Eg:for x in (1, 2)print x  = 1,2 



Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −
L = {'abc','xyz','rtu'}


1)Offsets start at zero

 Eg:L[2] = rtu


2)Negative: count from the right

 Eg:L[-2] = xyz


3)Slicing fetches sections

 Eg:L[1:] = ['xyz', 'rtu']

Python includes the following tuple functions −



1)cmp(tuple1, tuple2)


 Compares elements of both tuples.

2)len(tuple)


 Gives the total length of the tuple.

3max(tuple)


 Returns item from the tuple with max value.

4min(tuple)


 Returns item from the tuple with min value.

5tuple(seq)


 Converts a list into tuple.

List Usages

Lists

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.
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 which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For example 
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

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. For example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

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

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. For example −
#!/usr/bin/python

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]
Note: append() method is discussed in subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 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. For example −
#!/usr/bin/python

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]
Note: remove() method is discussed in subsequent section.

Basic List Operations


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.

 1)Length

     Eg: len([1,2]) =2

2)Concat

     Eg: [1.2,3] + [4,5,6] = [1, 2, 3, 4, 5, 6]


3)Repetition 

   Eg:('Hi',) * 2  = ['Hi','Hi']

4)Membership

  Eg:3 in [1, 2, 3] = True

5)Iteration

  Eg:for x in [1, 2]print x  = 1,2 


Index and Slicing:


1)Offsets start at zero

 Eg:L[2] = 'SPAM!'


2)Negative: count from the right

 Eg:L[-2] = 'Spam'


3)Slicing fetches sections

 Eg:L[1:] = ['xyz', 'rtu']

Built-in List Functions & Methods:



1)cmp(list1, list2)


 Compares elements of both lists.

2)len(list)


 Gives the total length of the list.

3)max(list)


 Returns item from the list with max value.

4)min(list)


 Returns item from the list with min value.

5)list(seq)

 Converts a tuple into list.

Python includes following list methods

1)list.append(obj)


 Appends object obj to list

2)list.count(obj)


 Returns count of how many times obj occurs in list

3)list.extend(seq)


 Appends the contents of seq to list

4)list.index(obj)


 Returns the lowest index in list that obj appears

5)list.insert(index, obj)


 Inserts object obj into list at offset index

6)list.pop(obj=list[-1])


 Removes and returns last object or obj from list

7)list.remove(obj)


 Removes object obj from list

8)list.reverse()


 Reverses objects of list in place

9)list.sort([func])


 Sorts objects of list, use compare func if given

Lets Write some scripts using Python

Magic 8ball Script



#! /usr/bin/env python
import sys,re,random

while True:
      x = raw_input("Please ask a question: ")
      n = random.randint(1, 7)
      if re.match("^exit$|^close$", x):
            print "GoodBye!"
            sys.exit()
      elif n == 1:
            print "The answer lies in your heart"
      elif n == 2:
            print "I do not know"
      elif n == 3:
            print "Almost certainly"
      elif n == 4:
            print "No"
      elif n == 5:
            print "Why do you need to ask?"
      elif n == 6:
            print "Go away. I do not wish to answer at this time."
      elif n == 7:
            print "Time will only tell"


Finding Specified Files


Here am searching all mp3 files in system.

import fnmatch
import os
rootPath = '/'
pattern = '*.mp3'
for root,dirs,files in os.walk(rootPath):
      for filename in fnmatch.filter(files,pattern):
            print(os.path.join(root,filename))


Date and Time Script



from datetime import datetime
now = datetime.now()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print mm + "/" +dd + "/" +yyyy +" " + hour + ":"+mi +":"+ss

Lets Play with Date in Python....

Getting Fromated Time


import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime

Output
Local current time : Tue Jan 13 10:17:09 2009

Getting Calendar For A Month

#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;

Output
Here is the calendar:
    January 2008
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
              

How To Convert Date to DateTime

Example:

import datetime
import dateutil.relativedelta from datetime import date, timedelta date_from = obj.date_from//we are taking date(2014-6-11) date_to = obj.date_to//date formate date_from = datetime.datetime.strptime(obj.date_from, "%Y-%m-%d") date_to = datetime.datetime.strptime(obj.date_to, "%Y-%m-%d")

output
date_from = 2014-6-11 00:00:00



How Many Month Between Two Dates

1)first Convert date in to datetime objects(Refer previous) 2)Month = (12 * date_to.year + date_to.month) - (12 * date_from.year + date_from.month)




 

How To Print Current Date Time


from datetime import datetime
from dateutil.relativedelta import relativedelta
import time
from math import *

today_current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

today_current_datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 

Finding Days, Hours,Minutes,seconds between Two Dates


from datetime import datetime
from dateutil.relativedelta import relativedelta
import time
from math import *

start_date = task.work_id.date (Normal Date)
end_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') (current datetime)
duration = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S') - datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')


days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
hours_toupdate = int(hours) + (float(minutes)/60)

How To Add One Day To The Date


from datetime import datetime,date
from datetime import timedelta

production_date_planned_from = datetime.strptime(production_date_planned,"%Y-%m-%d") // production_date_planned normal date
production_date_planned_to = production_date_planned_from + timedelta(days=1)



How To add Months to Date


import datetime
import dateutil.relativedelta
from datetime import date, timedelta

date_from = obj.date_from (normal date)
date_from_str =str(date_from)
d = datetime.datetime.strptime(date_from_str, "%Y-%m-%d")
new_date= d – dateutil.relativedelta.relativedelta(months=int(7))//substracting 7 months




How Can I convert Datetime to Date


from dateutil.relativedelta import relativedelta
import time
from math import *
from datetime import datetime

production_date_planned_to =2014-08-17 00:00:00

date = production_date_planned_to.strftime('%Y/%m/%d')
2014/08/17


How can I find Periods From Date


period_pool = self.pool.get('account.period')
search_periods = period_pool.find(cr, uid, slip.date_to, context=ctx)
period_id = search_periods[0]
period_from_date_value = period_from_date_value.with_context().find(date_value)[:1]
period_id = period_from_date_value.id





Year start date and end date


start_date = date(date.today().year, 1, 1) date
end_date = date(date.today().year, 12, 31)

year_start_date = str(datetime.strptime(str(date(date.today().year, 1, 1)), "%Y-%m-%d"))
year_end_date = str(datetime.strptime(str(date(date.today().year, 12, 31)), "%Y-%m-%d")) date time


Getting Year from Datetime


leave.date_from.split('-')[0] year
leave.date_from.split('-')[1] month

leave.date_from.split('-')[0] day

How to get Current Date


fields.date.today()


Saturday, 1 August 2015

Dictionary Manipulation In Python

 Dictionary:


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, 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. Following is a simple example

#!/usr/bin/python

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

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

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

#!/usr/bin/python

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

print "dict['Alice']: ", dict['Alice']

dict['Zara']:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary:


You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −



#!/usr/bin/python

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

Built-in Dictionary Functions & Methods −


1)cmp(dict1, dict2)

  Compares elements of both dict.

2)len(dict)

  Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3)str(dict)

  Produces a printable string representation of a dictionary

4)type(variable)

  Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Methods with Description



1)dict.clear()

 Removes all elements of dictionary dict

2)dict.copy()

 Returns a shallow copy of dictionary dict

3)dict.fromkeys()

 Create a new dictionary with keys from seq and values set to value.

4)dict.get(key, default=None)

 For key key, returns value or default if key not in dictionary

5)dict.has_key(key)

 Returns true if key in dictionary dict, false otherwise

6)dict.items()

 Returns a list of dict's (key, value) tuple pairs

7)dict.keys()

 Returns list of dictionary dict's keys

8)dict.setdefault(key, default=None)

 Similar to get(), but will set dict[key]=default if key is not already in dict

9)dict.update(dict2)

 Adds dictionary dict2's key-values pairs to dict

Introduction to Python

Features of Python


Simple



Python is a simple and minimalistic language. Reading a good Python program feels
almost like reading English, although very strict English! This pseudo-code nature
of Python is one of its greatest strengths. It allows you to concentrate on the solution
to the problem rather than the language itself.

Easy to Learn



As you will see, Python is extremely easy to get started with. Python has an
extraordinarily simple syntax, as already mentioned.

Free and Open Source



Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple
terms, you can freely distribute copies of this software, read its source code, make
changes to it, and use pieces of it in new free programs. FLOSS is based on the
concept of a community which shares knowledge. This is one of the reasons why
Python is so good - it has been created and is constantly improved by a community
who just want to see a better Python.

High-level Language



When you write programs in Python, you never need to bother about the low-level
details such as managing the memory used by your program, etc.

Portable



Due to its open-source nature, Python has been ported to (i.e. changed to make
it work on) many platforms. All your Python programs can work on any of these
platforms without requiring any changes at all if you are careful enough to avoid any
system-dependent features.
You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2,
Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn
RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC!
You can even use a platform like Kivy1
 to create games for your computer and for
iPhone, iPad, and Android.

Interpreted



This requires a bit of explanation.
A program written in a compiled language like C or C[]+ is converted from the source
language i.e. C or C+ into a language that is spoken by your computer (binary code
i.e. 0s and 1s) using a compiler with various flags and options. When you run the
program, the linker/loader software copies the program from hard disk to memory
and starts running it.


Object Oriented



Python supports procedure-oriented programming as well as object-oriented
programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In
object-oriented languages, the program is built around objects which combine data
and functionality. Python has a very powerful but simplistic way of doing OOP,
especially when compared to big languages like C++ or Java.

Extensible



If you need a critical piece of code to run very fast or want to have some piece of
algorithm not to be open, you can code that part of your program in C or C\++ and
then use it from your Python program.

Embeddable



You can embed Python within your C/C\++ programs to give scripting capabilities
for your program’s users.




Operators



We will briefly take a look at the operators and their usage.
Note that you can evaluate the expressions given in the examples using the interpreter
interactively. For example, to test the expression 2 + 3 , use the interactive Python
interpreter prompt:
>>> 2 + 3
5
>>> 3 * 5
15
>>>
Here is a quick overview of the available operators:


+ (plus)



Adds two objects
3 + 5 gives 8 . 'a' + 'b' gives 'ab' .


- (minus)



Gives the subtraction of one number from the other; if the first operand is absent
it is assumed to be zero.
-5.2 gives a negative number and 50 - 24 gives 26 .

* (multiply)



Gives the multiplication of the two numbers or returns the string repeated that many
times.
2 * 3 gives 6 . 'la' * 3 gives 'lalala' .Operators and Expressions
50

** (power)



Returns x to the power of y
3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3 )

/ (divide)



Divide x by y
13 / 3 gives 4 . 13.0 / 3 gives 4.333333333333333

% (modulo)



Returns the remainder of the division

13 % 3 gives 1 . -25.5 % 2.25 gives 1.5 .


<< (left shift)



Shifts the bits of the number to the left by the number of bits specified. (Each number
is represented in memory by bits or binary digits i.e. 0 and 1)
2 << 2 gives 8 . 2 is represented by 10 in bits.
Left shifting by 2 bits gives 1000 which represents the decimal 8 .

>> (right shift)



Shifts the bits of the number to the right by the number of bits specified.
11 >> 1 gives 5 .
11 is represented in bits by 1011 which which when right shifted by 1 bit gives
101`which is the decimal `5 .

& (bit-wise AND)



Bit-wise AND of the numbers
5 & 3 gives 1 .

| (bit-wise OR)



Bitwise OR of the numbers
5 | 3 gives 7

^ (bit-wise XOR)



Bitwise XOR of the numbers
5 ^ 3 gives 6


~ (bit-wise invert)



The bit-wise inversion of x is -(x+1)
~5 gives -6 . More details at http://stackoverflow.com/a/11810203

< (less than)



Returns whether x is less than y. All comparison operators return True or False .
Note the capitalization of these names.
5 < 3 gives False and 3 < 5 gives True .
Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True .

> (greater than)



Returns whether x is greater than y
5 > 3 returns True . If both operands are numbers, they are first converted to a
common type. Otherwise, it always returns False .

# (less than or equal to)



Returns whether x is less than or equal to y
x = 3; y = 6; x # y returns True .

>= (greater than or equal to)



Returns whether x is greater than or equal to y
x = 4; y = 3; x >= 3 returns True .

== (equal to)



Compares if the objects are equal
x = 2; y = 2; x == y returns True .
x = 'str'; y = 'stR'; x == y returns False .
x = 'str'; y = 'str'; x == y returns True .

!= (not equal to)



Compares if the objects are not equal
x = 2; y = 3; x != y returns True .

not (boolean NOT)



If x is True , it returns False . If x is False , it returns True .perators and Expressions
52
x = True; not x returns False .

and (boolean AND)



x and y returns False if x is False , else it returns evaluation of y
x = False; y = True; x and y returns False since x is False. In
this case, Python will not evaluate y since it knows that the left hand side of the
'and' expression is False which implies that the whole expression will be False
irrespective of the other values. This is called short-circuit evaluation.

or (boolean OR)



If x is True , it returns True, else it returns evaluation of y
x = True; y = False; x or y returns True . Short-circuit evaluation applies
here as well.

Data Types



Numbers



Numbers are mainly of two types - integers and floats.
An examples of an integer is 2 which is just a whole number.
Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4 . The
E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10^-4^.
Note for Experienced Programmers
There is no separate long type. The int type can be an integer of
any size.

Strings



A string is a sequence of characters. Strings are basically just a bunch of words.
You will be using strings in almost every Python program that you write, so pay attention
to the following part.

Single Quote



You can specify strings using single quotes such as 'Quote me on this' .
All white space i.e. spaces and tabs, within the quotes, are preserved as-is.

Double Quotes



Strings in double quotes work exactly the same way as strings in single quotes. An
example is "What’s your name?" .

Triple Quotes



You can specify multi-line strings using triple quotes - ( """ or ''' ). You can use
single quotes and double quotes freely within the triple quotes. An example is:
'''This is a multi-line string. This is the first line.Basics
39
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''

Strings Are Immutable



This means that once you have created a string, you cannot change it. Although this
might seem like a bad thing, it really isn’t. We will see why this is not a limitation in the
various programs that we see later on.


Control Flow


The if statement



The if statement is used to check a condition: if the condition is true, we run a block of
statements (called the if-block), else we process another block of statements (called
the else-block). The else clause is optional.

Example (sa
7
ve as if.py):
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
 # New block starts here
 print 'Congratulations, you guessed it.'
 print '(but you do not win any prizes!)'
 # New block ends here
elif guess < number:
 # Another block
 print 'No, it is a little higher than that'
 # You can do whatever you want in a block ...
else:
 print 'No, it is a little lower than that'
 # you must have guessed > number to reach here
print 'Done'
# This last statement is always executed,
# after the if statement is executed.
Output:
$ python if.pyontrol Flow
57
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

The while Statement



The while statement allows you to repeatedly execute a block of statements as long
as a condition is true. A while statement is an example of what is called a looping
statement. A while statement can have an optional else clause.

Example (save as while.py ):
number = 23
running = True
while running:
 guess = int(raw_input('Enter an integer : '))
 if guess == number:
 print 'Congratulations, you guessed it.'ontrol Flow
59
 # this causes the while loop to stop
 running = False
 elif guess < number:
 print 'No, it is a little higher than that.'
 else:
 print 'No, it is a little lower than that.'
else:
 print 'The while loop is over.'
 # Do anything else you want to do here
print 'Done'
Output:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

The for loop




The for..in statement is another looping statement which iterates over a sequence
of objects i.e. go through each item in a sequence. We will see more about sequences
in detail in later chapters. What you need to know right now is that a sequence is just
an ordered collection of items.

Example (save as for.py ):
for i in range(1, 5):
 print i
else:
 print 'The for loop is over'
Output:
$ python for.py
1
2
3
4
The for loop is over


The break Statement



The break statement is used to break out of a loop statement i.e. stop the execution of
a looping statement, even if the loop condition has not become False or the sequence
of items has not been completely iterated over.
An important note is that if you break out of a for or while loop, any corresponding
loop else block is not executed.

Example (save as break.py ):
while True:
 s = raw_input('Enter something : ')
 if s == 'quit':
 break
 print 'Length of the string is', len(s)
print 'Done'
Output:ontrol Flow
62
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done


The continue Statement



The continue statement is used to tell Python to skip the rest of the statements in
the current loop block and to continue to the next iteration of the loop.

Example (save as continue.py ):
while True:ontrol Flow
63
 s = raw_input('Enter something : ')
 if s == 'quit':
 break
 if len(s) < 3:
 print 'Too small'
 continue
 print 'Input is of sufficient length'
 # Do other kinds of processing here...
Output:
$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit


Data Structures


List



A list is a data structure that holds an ordered collection of items i.e. you can store
a sequence of items in a list. This is easy to imagine if you can think of a shopping list
where you have a list of items to buy, except that you probably have each item on a
separate line in your shopping list whereas in Python you put commas in between them.
The list of items should be enclosed in square brackets so that Python understands
that you are specifying a list. Once you have created a list, you can add, remove or
search for items in the list. Since we can add and remove items, we say that a list is
a mutable data type i.e. this type can be altered.


Example (save as ds_using_list.py ):

# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist), 'items to purchase.'
print 'These items are:',
for item in shoplist:
 print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist
Output:
$ python ds_using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']


Tuple



Tuples are used to hold together multiple objects. Think of them as similar to lists, but
without the extensive functionality that the list class gives you. One major feature of
tuples is that they are immutable like strings i.e. you cannot modify tuples.
Tuples are defined by specifying items separated by commas within an optional pair
of parentheses.
Tuples are usually used in cases where a statement or a user-defined function can
safely assume that the collection of values i.e. the tuple of values used will not change.


Example (save as ds_using_tuple.py ):
# I would recommend always using parenthesesata Structures
85
# to indicate start and end of tuple
# even though parentheses are optional.
# Explicit is better than implicit.
zoo = ('python', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = 'monkey', 'camel', zoo
print 'Number of cages in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
print 'Number of animals in the new zoo is', \
 len(new_zoo)-1+len(new_zoo[2])

Output:

$ python ds_using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant',
 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5



Dictionary



A dictionary is like an address-book where you can find the address or contact details
of a person by knowing only his/her name i.e. we associate keys (name) with values
(details). Note that the key must be unique just like you cannot find out the correct
information if you have two persons with the exact same name.
Note that you can use only immutable objects (like strings) for the keys of a dictionary
but you can use either immutable or mutable objects for the values of the dictionary.
This basically translates to say that you should use only simple objects for keys.
Pairs of keys and values are specified in a dictionary by using the notation d =
{key1 : value1, key2 : value2 } . Notice that the key-value pairs are separated
by a colon and the pairs are separated themselves by commas and all this is enclosed
in a pair of curly braces.
Remember that key-value pairs in a dictionary are not ordered in any manner. If you
want a particular order, then you will have to sort them yourself before using it.
The dictionaries that you will be using are instances/objects of the dict class.



Example (save as ds_using_dict.py ):
# 'ab' is short for 'a'ddress'b'ook
ab = { 'Swaroop' : 'swaroop@swaroopch.com',
 'Larry' : 'larry@wall.org',
 'Matsumoto' : 'matz@ruby-lang.org',
 'Spammer' : 'spammer@hotmail.com'ata Structures
87
 }
print "Swaroop's address is", ab['Swaroop']
# Deleting a key-value pair
del ab['Spammer']
print '\nThere are {} contacts in the address-book\n'.format(len(ab))
for name, address in ab.items():
 print 'Contact {} at {}'.format(name, address)
# Adding a key-value pair
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
 print "\nGuido's address is", ab['Guido']

Output:

$ python ds_using_dict.py
Swaroop's address is swaroop@swaroopch.com
There are 3 contacts in the address-book
Contact Swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Guido's address is guido@python.org



Sequence

Lists, tuples and strings are examples of sequences, but what are sequences and what
is so special about them?
The major features are membership tests, (i.e. the in and not in expressions)
and indexing operations, which allow us to fetch a particular item in the sequence
directly.
The three types of sequences mentioned above - lists, tuples and strings, also have
a slicing operation which allows us to retrieve a slice of the sequence i.e. a part of
the sequence.

Example (save as ds_seq.py ):

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]ata Structures
89
print 'Item -2 is', shoplist[-2]
print 'Character 0 is', name[0]
# Slicing on a list #
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string #
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

Output:

$ python ds_seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop


 Set



Sets are unordered collections of simple objects. These are used when the existence of
an object in a collection is more important than the order or how many times it occurs.
Using sets, you can test for membership, whether it is a subset of another set, find the
intersection between two sets, and so on.

>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}



References



When you create an object and assign it to a variable, the variable only refers to the
object and does not represent the object itself! That is, the variable name points to that
part of your computer’s memory where the object is stored. This is called binding the
name to the object.
Generally, you don’t need to be worried about this, but there is a subtle effect due to
references which you need to be aware of:
Example (save as ds_reference.py ):
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist is just another name pointing to the same object!
mylist = shoplistata Structures
92
# I purchased the first item, so I remove it from the list
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# Notice that both shoplist and mylist both print
# the same list without the 'apple' confirming that
# they point to the same object
print 'Copy by making a full slice'
# Make a copy by doing a full slice
mylist = shoplist[:]
# Remove first item
del mylist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# Notice that now the two lists are different

Output:

$ python ds_reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']