Features of Python
Simple
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
extraordinarily simple syntax, as already mentioned.
Free and Open Source
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
details such as managing the memory used by your program, etc.
Portable
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
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
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
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
for your program’s users.
Operators
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)
3 + 5 gives 8 . 'a' + 'b' gives 'ab' .
- (minus)
it is assumed to be zero.
-5.2 gives a negative number and 50 - 24 gives 26 .
* (multiply)
times.
2 * 3 gives 6 . 'la' * 3 gives 'lalala' .Operators and Expressions
50
** (power)
3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3 )
/ (divide)
13 / 3 gives 4 . 13.0 / 3 gives 4.333333333333333
% (modulo)
13 % 3 gives 1 . -25.5 % 2.25 gives 1.5 .
<< (left shift)
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)
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)
5 & 3 gives 1 .
| (bit-wise OR)
5 | 3 gives 7
^ (bit-wise XOR)
5 ^ 3 gives 6
~ (bit-wise invert)
~5 gives -6 . More details at http://stackoverflow.com/a/11810203
< (less than)
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)
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)
x = 3; y = 6; x # y returns True .
>= (greater than or equal to)
x = 4; y = 3; x >= 3 returns True .
== (equal to)
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)
x = 2; y = 3; x != y returns True .
not (boolean NOT)
52
x = True; not x returns False .
and (boolean AND)
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)
x = True; y = False; x or y returns True . Short-circuit evaluation applies
here as well.
Data Types
Numbers
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
You will be using strings in almost every Python program that you write, so pay attention
to the following part.
Single Quote
All white space i.e. spaces and tabs, within the quotes, are preserved as-is.
Double Quotes
example is "What’s your name?" .
Triple Quotes
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
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']
No comments:
Post a Comment