Python Programming Document
Python Programming Document
$ python if.py
Enter an integer : 22Python en:Control Flow 39
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
How It Works:
In this program, we take guesses from the user and check if it is the number that we have.
We set the variable number to any integer we want, say 23. Then, we take the user's guess
using the input() function. Functions are just reusable pieces of programs. We'll read
more about them in the next chapter.
We supply a string to the built-in input function which prints it to the screen and waits for
input from the user. Once we enter something and press enter key, the input() function
returns what we entered, as a string. We then convert this string to an integer using int
and then store it in the variable guess. Actually, the int is a class but all you need to know
right now is that you can use it to convert a string to an integer (assuming the string
contains a valid integer in the text).
Next, we compare the guess of the user with the number we have chosen. If they are equal,
we print a success message. Notice that we use indentation levels to tell Python which
statements belong to which block. This is why indentation is so important in Python. I hope
you are sticking to the "consistent indentation" rule. Are you?
Notice how the if statement contains a colon at the end - we are indicating to Python that
a block of statements follows.
Then, we check if the guess is less than the number, and if so, we inform the user to guess
a little higher than that. What we have used here is the elif clause which actually
combines two related if else-if else statements into one combined if-elif-else
statement. This makes the program easier and reduces the amount of indentation required.
The elif and else statements must also have a colon at the end of the logical line
followed by their corresponding block of statements (with proper indentation, of course)
You can have another if statement inside the if-block of an if statement and so on - this is
called a nested if statement.
Remember that the elif and else parts are optional. A minimal valid if statement is:
if True:
print('Yes, it is true')
After Python has finished executing the complete if statement along with the associated
elif and else clauses, it moves on to the next statement in the block containing the if
statement. In this case, it is the main block where execution of the program starts and the
next statement is the print('Done') statement. After this, Python sees the ends of the
program and simply finishes up.
Although this is a very simple program, I have been pointing out a lot of things that you
should notice even in this simple program. All these are pretty straightforward (and
surprisingly simple for those of you from C/C++ backgrounds) and requires you to
becomePython en:Control Flow 40
aware of all these initially, but after that, you will become comfortable with it and it'll feel
'natural' to you.
Note for C/C++ Programmers
There is no switch statement in Python. You can use an if..elif..else statement to
do the same thing (and in some cases, use a dictionary to do it quickly)
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:
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop
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
How It Works:Python en:Control Flow 41
In this program, we are still playing the guessing game, but the advantage is that the user
is allowed to keep guessing until he guesses correctly - there is no need to repeatedly run
the program for each guess, as we have done in the previous section. This aptly
demonstrates the use of the while statement.
We move the input and if statements to inside the while loop and set the variable
running to True before the while loop. First, we check if the variable running is True and
then proceed to execute the corresponding while-block. After this block is executed, the
condition is again checked which in this case is the running variable. If it is true, we
execute the while-block again, else we continue to execute the optional else-block and then
continue to the next statement.
The else block is executed when the while loop condition becomes False - this may even
be the first time that the condition is checked. If there is an else clause for a while loop,
it is always executed unless you break out of the loop with a break statement.
The True and False are called Boolean types and you can consider them to be equivalent
to the value 1 and 0 respectively.
Note for C/C++ Programmers
Remember that you can have an else clause for the while loop.
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:
#!/usr/bin/python
# Filename: 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
How It Works:
In this program, we are printing a sequence of numbers. We generate this sequence of
numbers using the built-in range function.
What we do here is supply it two numbers and range returns a sequence of numbers
starting from the first number and up to the second number. For example, range(1,5)Python
en:Control Flow 42
gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1. If we supply a
third number to range, then that becomes the step count. For example, range(1,5,2)
gives [1,3]. Remember that the range extends up to the second number i.e. it does not
include the second number.
The for loop then iterates over this range - for i in range(1,5) is equivalent to for i
in [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i, one
at a time, and then executing the block of statements for each value of i. In this case, we
just print the value in the block of statements.
Remember that the else part is optional. When included, it is always executed once after
the for loop is over unless a break statement is encountered.
Remember that the for..in loop works for any sequence. Here, we have a list of numbers
generated by the built-in range function, but in general we can use any kind of sequence of
any kind of objects! We will explore this idea in detail in later chapters.
Note for C/C++/Java/C# Programmers
The Python for loop is radically different from the C/C++ for loop. C# programmers
will note that the for loop in Python is similar to the foreach loop in C#. Java
programmers will note that the same is similar to for (int i : IntArray) in Java
1.5 .
In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Python you
write just for i in range(0,5). As you can see, the for loop is simpler, more
expressive and less error prone in Python.
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 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:
#!/usr/bin/python
# Filename: break.py
while True:
s = (input('Enter something : '))
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Output:
$ 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 21Python en:Control Flow 43
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 12
Enter something : quit
Done
How It Works:
In this program, we repeatedly take the user's input and print the length of each input each
time. We are providing a special condition to stop the program by checking if the user input
is 'quit'. We stop the program by breaking out of the loop and reach the end of the
program.
The length of the input string can be found out using the built-in len function.
Remember that the break statement can be used with the for loop as well.
Swaroop's Poetic Python
The input I have used here is a mini poem I have written called Swaroop's Poetic Python:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
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:
#!/usr/bin/python
# Filename: continue.py
while True:
s = 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 test.py
Enter something : a
Too small
Enter something : 12
Too smallPython en:Control Flow 44
Enter something : abc
Input is of sufficient length
Enter something : quit
How It Works:
In this program, we accept input from the user, but we process them only if they are at
least 3 characters long. So, we use the built-in len function to get the length and if the
length is less than 3, we skip the rest of the statements in the block by using the continue
statement. Otherwise, the rest of the statements in the loop are executed and we can do
any kind of processing we want to do here.
Note that the continue statement works with the for loop as well.
Summary
We have seen how to use the three control flow statements - if, while and for along with
their associated break and continue statements. These are some of the most often used
parts of Python and hence, becoming comfortable with them is essential.
Next, we will see how to create and use functions.
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1664
Contributors: Swaroop, 8 anonymous edits
Python en:Functions
Introduction
Functions are reusable pieces of programs. They allow you to give a name to a block of
statements and you can run that block using that name anywhere in your program and any
number of times. This is known as calling the function. We have already used many built-in
functions such as the len and range.
The function concept is probably the most important building block of any non-trivial
software (in any programming language), so we will explore various aspects of functions in
this chapter.
Functions are defined using the def keyword. This is followed by an identifier name for the
function followed by a pair of parentheses which may enclose some names of variables and
the line ends with a colon. Next follows the block of statements that are part of this
function. An example will show that this is actually very simple:
Example:
#!/usr/bin/python
# Filename: function1.py
def sayHello():
print('Hello World!') # block belonging to the function
# End of functionPython en:Functions 45
sayHello() # call the function
sayHello() # call the function again
Output:
$ python function1.py
Hello World!
Hello World!
How It Works:
We define a function called sayHello using the syntax as explained above. This function
takes no parameters and hence there are no variables declared in the parentheses.
Parameters to functions are just input to the function so that we can pass in different values
to it and get back corresponding results.
Notice that we can call the same function twice which means we do not have to write the
same code again.
Function Parameters
A function can take parameters, which are values you supply to the function so that the
function can do something utilising those values. These parameters are just like variables
except that the values of these variables are defined when we call the function and are
already assigned values when the function runs.
Parameters are specified within the pair of parentheses in the function definition, separated
by commas. When we call the function, we supply the values in the same way. Note the
terminology used - the names given in the function definition are called parameters
whereas the values you supply in the function call are called arguments.
Example:
#!/usr/bin/python
# Filename: func_param.py
def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4) # directly give literal values
x=5
y=7
printMax(x, y) # give variables as arguments
Output:Python en:Functions 46
$ python func_param.py
4 is maximum
7 is maximum
How It Works:
Here, we define a function called printMax where we take two parameters called a and b.
We find out the greater number using a simple if..else statement and then print the
bigger number.
In the first usage of printMax, we directly supply the numbers i.e. arguments. In the second
usage, we call the function using variables. printMax(x, y) causes value of argument x to
be assigned to parameter a and the value of argument y assigned to parameter b. The
printMax function works the same in both the cases.
Local Variables
When you declare variables inside a function definition, they are not related in any way to
other variables with the same names used outside the function i.e. variable names are local
to the function. This is called the scope of the variable. All variables have the scope of the
block they are declared in starting from the point of definition of the name.
Example:
#!/usr/bin/python
# Filename: func_local.py
x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is still', x)
Output:
$ python func_local.py
x is 50
Changed local x to 2
x is still 50
How It Works:
In the function, the first time that we use the value of the name x, Python uses the value of
the parameter declared in the function.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change
the value of x in the function, the x defined in the main block remains unaffected.
In the last print function call, we display the value of x in the main block and confirm that
it is actually unaffected.Python en:Functions 47
Using The global Statement
If you want to assign a value to a name defined at the top level of the program (i.e. not
inside any kind of scope such as functions or classes), then you have to tell Python that the
name is not local, but it is global. We do this using the global statement. It is impossible to
assign a value to a variable defined outside a function without the global statement.
You can use the values of such variables defined outside the function (assuming there is no
variable with the same name within the function). However, this is not encouraged and
should be avoided since it becomes unclear to the reader of the program as to where that
variable's definition is. Using the global statement makes it amply clear that the variable
is defined in an outermost block.
Example:
#!/usr/bin/python
# Filename: func_global.py
x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
Output:
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2
How It Works:
The global statement is used to declare that x is a global variable - hence, when we assign
a value to x inside the function, that change is reflected when we use the value of x in the
main block.
You can specify more than one global variable using the same global statement. For
example, global x, y, z.Python en:Functions 48
Using nonlocal statement
We have seen how to access variables in the local and global scope above. There is another
kind of scope called "nonlocal" scope which is in-between these two types of scopes.
Nonlocal scopes are observed when you define functions inside functions.
Since everything in Python is just executable code, you can define functions anywhere.
Let's take an example:
#!/usr/bin/python
# Filename: func_nonlocal.py
def func_outer():
x=2
print('x is', x)
def func_inner():
nonlocal x
x=5
func_inner()
print('Changed local x to', x)
func_outer()
Output:
$ python func_nonlocal.py
x is 2
Changed local x to 5
How It Works:
When we are inside func_inner, the 'x' defined in the first line of func_outer is relatively
neither in local scope nor in global scope. We declare that we are using this x by nonlocal
x and hence we get access to that variable.
Try changing the nonlocal x to global x and also by removing the statement itself and
observe the difference in behavior in these two cases.
Default Argument Values
For some functions, you may want to make some of its parameters as optional and use
default values if the user does not want to provide values for such parameters. This is done
with the help of default argument values. You can specify default argument values for
parameters by following the parameter name in the function definition with the assignment
operator (=) followed by the default value.
Note that the default argument value should be a constant. More precisely, the default
argument value should be immutable - this is explained in detail in later chapters. For now,
just remember this.
Example:Python en:Functions 49
#!/usr/bin/python
# Filename: func_default.py
def say(message, times = 1):
print(message * times)
say('Hello')
say('World', 5)
Output:
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
How It Works:
The function named say is used to print a string as many times as specified. If we don't
supply a value, then by default, the string is printed just once. We achieve this by specifying
a default argument value of 1 to the parameter times.
In the first usage of say, we supply only the string and it prints the string once. In the
second usage of say, we supply both the string and an argument 5 stating that we want to
say the string message 5 times.
Important
Only those parameters which are at the end of the parameter list can be given default
argument values i.e. you cannot have a parameter with a default argument value
before a parameter without a default argument value in the order of parameters
declared in the function parameter list.
This is because the values are assigned to the parameters by position. For example,
def func(a, b=5) is valid, but def func(a=5, b) is not valid.
Keyword Arguments
If you have some functions with many parameters and you want to specify only some of
them, then you can give values for such parameters by naming them - this is called keyword
arguments - we use the name (keyword) instead of the position (which we have been using
all along) to specify the arguments to the function.
There are two advantages - one, using the function is easier since we do not need to worry
about the order of the arguments. Two, we can give values to only those parameters which
we want, provided that the other parameters have default argument values.
Example:
#!/usr/bin/python
# Filename: func_key.py
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)Python en:Functions 50
func(25, c=24)
func(c=50, a=100)
Output:
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
How It Works:
The function named func has one parameter without default argument values, followed by
two parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 7 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position
of the argument. Then, the parameter c gets the value of 24 due to naming i.e. keyword
arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments completely to specify
the values. Notice, that we are specifying value for parameter c before that for a even
though a is defined before c in the function definition.
VarArgs parameters
TODO
Should I write about this in a later chapter since we haven't talked about lists and
dictionaries yet?
Sometimes you might want to define a function that can take any number of parameters,
this can be achieved by using the stars:
#!/usr/bin/python
# Filename: total.py
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
Output:
$ python total.py
166
How It Works:Python en:Functions 51
When we declare a starred parameter such as *param, then all the positional arguments
from that point till the end are collected as a list called 'param'.
Similarly, when we declare a double-starred parameter such as **param, then all the
keyword arguments from that point till the end are collected as a dictionary called 'param'.
We will explore lists and dictionaries in a later chapter.
Keyword-only Parameters
If we want to specify certain keyword parameters to be available as keyword-only and not
as positional arguments, they can be declared after a starred parameter:
#!/usr/bin/python
# Filename: keyword_only.py
def total(initial=5, *numbers, vegetables):
count = initial
for number in numbers:
count += number
count += vegetables
return count
print(total(10, 1, 2, 3, vegetables=50))
print(total(10, 1, 2, 3))
# Raises error because we have not supplied a default argument value
for 'vegetables'
Output:
$ python keyword_only.py
66
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(total(10, 1, 2, 3))
TypeError: total() needs keyword-only argument vegetables
How It Works:
Declaring parameters after a starred parameter results in keyword-only arguments. If these
arguments are not supplied a default value, then calls to the function will raise an error if
the keyword argument is not supplied, as seen above.
If you want to have keyword-only arguments but have no need for a starred parameter, then
simply use an empty star without using any name such as def total(initial=5, *,
vegetables).Python en:Functions 52
The return Statement
The return statement is used to return from a function i.e. break out of the function. We
can optionally return a value from the function as well.
Example:
#!/usr/bin/python
# Filename: func_return.py
def maximum(x, y):
if x > y:
return x
else:
return y
print(maximum(2, 3))
Output:
$ python func_return.py
3
How It Works:
The maximum function returns the maximum of the parameters, in this case the numbers
supplied to the function. It uses a simple if..else statement to find the greater value and
then returns that value.
Note that a return statement without a value is equivalent to return None. None is a
special type in Python that represents nothingness. For example, it is used to indicate that a
variable has no value if it has a value of None.
Every function implicitly contains a return None statement at the end unless you have
written your own return statement. You can see this by running print(someFunction())
where the function someFunction does not use the return statement such as:
def someFunction():
pass
The pass statement is used in Python to indicate an empty block of statements.
Note
There is a built-in function called max that already implements the 'find maximum'
functionality, so use this built-in function whenever possible.Python en:Functions 53
DocStrings
Python has a nifty feature called documentation strings, usually referred to by its shorter
name docstrings. DocStrings are an important tool that you should make use of since it
helps to document the program better and makes it easier to understand. Amazingly, we
can even get the docstring back from, say a function, when the program is actually running!
Example:
#!/usr/bin/python
# Filename: func_doc.py
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
printMax(3, 5)
print(printMax.__doc__)
Output:
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
$ python backup_ver2.py
Successful backup to E:\Backup\20080702\202325.zip
How It Works:
Most of the program remains the same. The changes is that we check if there is a directory
with the current day as name inside the main backup directory using the os.path.exists
function. If it doesn't exist, we create it using the os.mkdir function.
Third Version
The second version works fine when I do many backups, but when there are lots of
backups, I am finding it hard to differentiate what the backups were for! For example, I
might have made some major changes to a program or presentation, then I want to
associate what those changes are with the name of the zip archive. This can be easily
achieved by attaching a user-supplied comment to the name of the zip archive.
Note
The following program does not work, so do not be alarmed, please follow along
because there's a lesson in here.
#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with
spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be
using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main
directory
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')Python en:Problem Solving 77
# Take a comment from the user to create the name of the zip file
comment = input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print('Successfully created directory', today)
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
Output:
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax
How This (does not) Work:
This program does not work! Python says there is a syntax error which means that the
script does not satisfy the structure that Python expects to see. When we observe the error
given by Python, it also tells us the place where it detected the error as well. So we start
debugging our program from that line.
On careful observation, we see that the single logical line has been split into two physical
lines but we have not specified that these two physical lines belong together. Basically,
Python has found the addition operator (+) without any operand in that logical line and
hence it doesn't know how to continue. Remember that we can specify that the logical line
continues in the next physical line by the use of a backslash at the end of the physical line.
So, we make this correction to our program. This correction of the program when we find
errors is called bug fixing.Python en:Problem Solving 78
Fourth Version
#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with
spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be
using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main
directory
today = target_dir + os.sep + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print('Successfully created directory', today)
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
Output:Python en:Problem Solving 79
$ python backup_ver4.py
Enter a comment --> added new examples
Successful backup to
E:\Backup\20080702\202836_added_new_examples.zip
$ python backup_ver4.py
Enter a comment -->
Successful backup to E:\Backup\20080702\202839.zip
How It Works:
This program now works! Let us go through the actual enhancements that we had made in
version 3. We take in the user's comments using the input function and then check if the
user actually entered something by finding out the length of the input using the len
function. If the user has just pressed enter without entering anything (maybe it was just a
routine backup or no special changes were made), then we proceed as we have done
before.
However, if a comment was supplied, then this is attached to the name of the zip archive
just before the .zip extension. Notice that we are replacing spaces in the comment with
underscores - this is because managing filenames without spaces are much easier.
More Refinements
The fourth version is a satisfactorily working script for most users, but there is always room
for improvement. For example, you can include a verbosity level for the program where you
can specify a -v option to make your program become more talkative.
Another possible enhancement would be to allow extra files and directories to be passed to
the script at the command line. We can get these names from the sys.argv list and we can
add them to our source list using the extend method provided by the list class.
The most important refinement would be to not use the os.system way of creating archives
and instead using the zipfile or tarfile built-in module to create these archives. They
are part of the standard library and available already for you to use without external
dependencies on the zip program to be available on your computer.
However, I have been using the os.system way of creating a backup in the above examples
purely for pedagogical purposes, so that the example is simple enough to be understood by
everybody but real enough to be useful.
Can you try writing the fifth version that uses the zipfile (http:/ /docs.python.org/dev/3.
0/library/zipfile.html) module instead of the os.system call?Python en:Problem Solving 80
The Software Development Process
We have now gone through the various phases in the process of writing a software. These
phases can be summarised as follows:
1. What (Analysis)
2. How (Design)
3. Do It (Implementation)
4. Test (Testing and Debugging)
5. Use (Operation or Deployment)
6. Maintain (Refinement)
A recommended way of writing programs is the procedure we have followed in creating the
backup script: Do the analysis and design. Start implementing with a simple version. Test
and debug it. Use it to ensure that it works as expected. Now, add any features that you
want and continue to repeat the Do It-Test-Use cycle as many times as required.
Remember, Software is grown, not built.
Summary
We have seen how to create our own Python programs/scripts and the various stages
involved in writing such programs. You may find it useful to create your own program just
like we did in this chapter so that you become comfortable with Python as well as
problem-solving.
Next, we will discuss object-oriented programming.
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1395
Contributors: Swaroop, 3 anonymous editsPython en:Object Oriented Programming 81
Python en:Object Oriented
Programming
Introduction
In all the programs we wrote till now, we have designed our program around functions i.e.
blocks of statements which manipulate data. This is called the procedure-oriented way of
programming. There is another way of organizing your program which is to combine data
and functionality and wrap it inside something called an object. This is called the object
oriented programming paradigm. Most of the time you can use procedural programming,
but when writing large programs or have a problem that is better suited to this method, you
can use object oriented programming techniques.
Classes and objects are the two main aspects of object oriented programming. A class
creates a new type where objects are instances of the class. An analogy is that you can
have variables of type int which translates to saying that variables that store integers are
variables which are instances (objects) of the int class.
Note for Static Language Programmers
Note that even integers are treated as objects (of the int class). This is unlike C++
and Java (before version 1.5) where integers are primitive native types. See
help(int) for more details on the class.
C# and Java 1.5 programmers will find this similar to the boxing and unboxing
concept.
Objects can store data using ordinary variables that belong to the object. Variables that
belong to an object or class are referred to as fields. Objects can also have functionality by
using functions that belong to a class. Such functions are called methods of the class. This
terminology is important because it helps us to differentiate between functions and
variables which are independent and those which belong to a class or object. Collectively,
the fields and methods can be referred to as the attributes of that class.
Fields are of two types - they can belong to each instance/object of the class or they can
belong to the class itself. They are called instance variables and class variables
respectively.
A class is created using the class keyword. The fields and methods of the class are listed
in an indented block.
The self
Class methods have only one specific difference from ordinary functions - they must have
an extra first name that has to be added to the beginning of the parameter list, but you do
not give a value for this parameter when you call the method, Python will provide it. This
particular variable refers to the object itself, and by convention, it is given the name self.
Although, you can give any name for this parameter, it is strongly recommended that you
use the name self - any other name is definitely frowned upon. There are many
advantages to using a standard name - any reader of your program will immediately
recognize it and even specialized IDEs (Integrated Development Environments) can help
you if you use self.Python en:Object Oriented Programming 82
Note for C++/Java/C# Programmers
The self in Python is equivalent to the this pointer in C++ and the this reference
in Java and C#.
You must be wondering how Python gives the value for self and why you don't need to
give a value for it. An example will make this clear. Say you have a class called MyClass
and an instance of this class called myobject. When you call a method of this object as
myobject.method(arg1, arg2), this is automatically converted by Python into
MyClass.method(myobject, arg1, arg2) - this is all the special self is about.
This also means that if you have a method which takes no arguments, then you still have to
have one argument - the self.
Classes
The simplest class possible is shown in the following example.
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
p = Person()
print(p)
Output:
$ python simplestclass.py
<__main__.Person object at 0x019F85F0>
How It Works:
We create a new class using the class statement and the name of the class. This is
followed by an indented block of statements which form the body of the class. In this case,
we have an empty block which is indicated using the pass statement.
Next, we create an object/instance of this class using the name of the class followed by a
pair of parentheses. (We will learn more about instantiation in the next section). For our
verification, we confirm the type of the variable by simply printing it. It tells us that we
have an instance of the Person class in the __main__ module.
Notice that the address of the computer memory where your object is stored is also printed.
The address will have a different value on your computer since Python can store the object
wherever it finds space.Python en:Object Oriented Programming 83
Object Methods
We have already discussed that classes/objects can have methods just like functions except
that we have an extra self variable. We will now see an example.
#!/usr/bin/python
# Filename: method.py
class Person:
def sayHi(self):
print('Hello, how are you?')
p = Person()
p.sayHi()
# This short example can also be written as Person().sayHi()
Output:
$ python method.py
Hello, how are you?
How It Works:
Here we see the self in action. Notice that the sayHi method takes no parameters but
still has the self in the function definition.
The __init__method
There are many method names which have special significance in Python classes. We will
see the significance of the __init__ method now.
The __init__ method is run as soon as an object of a class is instantiated. The method is
useful to do any initialization you want to do with your object. Notice the double
underscores both at the beginning and at the end of the name.
Example:
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print('Hello, my name is', self.name)
p = Person('Swaroop')
p.sayHi()
# This short example can also be written as Person('Swaroop').sayHi()
Output:Python en:Object Oriented Programming 84
$ python class_init.py
Hello, my name is Swaroop
How It Works:
Here, we define the __init__ method as taking a parameter name (along with the usual
self). Here, we just create a new field also called name. Notice these are two different
variables even though they are both called 'name'. The dotted notation allows us to
differentiate between them.
Most importantly, notice that we do not explicitly call the __init__ method but pass the
arguments in the parentheses following the class name when creating a new instance of the
class. This is the special significance of this method.
Now, we are able to use the self.name field in our methods which is demonstrated in the
sayHi method.
Class And Object Variables
We have already discussed the functionality part of classes and objects (i.e. methods), now
let us learn about the data part. The data part, i.e. fields, are nothing but ordinary variables
that are bound to the namespaces of the classes and objects. This means that these names
are valid within the context of these classes and objects only. That's why they are called
name spaces.
There are two types of fields - class variables and object variables which are classified
depending on whether the class or the object owns the variables respectively.
Class variables are shared - they can be accessed by all instances of that class. There is
only one copy of the class variable and when any one object makes a change to a class
variable, that change will be seen by all the other instances.
Object variables are owned by each individual object/instance of the class. In this case,
each object has its own copy of the field i.e. they are not shared and are not related in any
way to the field by the same name in a different instance. An example will make this easy to
understand:
#!/usr/bin/python
# Filename: objvar.py
class Robot:
'''Represents a robot, with a name.'''
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
'''Initializes the data.'''
self.name = name
print('(Initializing {0})'.format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1Python en:Object Oriented Programming 85
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots
working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''
print('Greetings, my masters call me {0}.'.format(self.name))
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
Output:
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.Python en:Object Oriented Programming 86
$ python user_input.py
Enter text: madam
Yes, it is a palindrome
$ python user_input.py
Enter text: racecar
Yes, it is a palindrome
How It Works:
We use the slicing feature to reverse the text. We've already seen how we can make slices
from sequences using the seq[a:b] code starting from position a to position b. We can
also provide a third argument that determines the step by which the slicing is done. ThePython
en:Input Output 91
default step is 1 because of which it returns a continuous part of the text. Giving a negative
step, i.e., -1 will return the text in reverse.
The input() function takes a string as argument and displays it to the user. Then it waits
for the user to type something and press the return key. Once the user has entered, the
input() function will then return that text.
We take that text and reverse it. If the original text and reversed text are equal, then the
text is a palindrome (http://en.wiktionary.org/wiki/palindrome).
Homework exercise:
Checking whether a text is a palindrome should also ignore punctuation, spaces and case.
For example, "Rise to vote, sir." is also a palindrome but our current program doesn't say it
is. Can you improve the above program to recognize this palindrome?
Files
You can open and use files for reading or writing by creating an object of the file class
and using its read, readline or write methods appropriately to read from or write to the
file. The ability to read or write to the file depends on the mode you have specified for the
file opening. Then finally, when you are finished with the file, you call the close method to
tell Python that we are done using the file.
Example:
#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed
by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print(line, end='')
f.close() # close the file
Output:
$ python using_file.py
Programming is funPython en:Input Output 92
When the work is done
if you wanna make your work also fun:
use Python!
How It Works:
First, open a file by using the built-in open function and specifying the name of the file and
the mode in which we want to open the file. The mode can be a read mode ('r'), write
mode ('w') or append mode ('a'). We can also by dealing with a text file ('t') or a binary
file ('b'). There are actually many more modes available and help(open) will give you
more details about them. By default, open() considers the file to be a 't'ext file and opens it
in 'r'ead mode.
In our example, we first open the file in write text mode and use the write method of the
file object to write to the file and then we finally close the file.
Next, we open the same file again for reading. We don't need to specify a mode because
'read text file' is the default mode. We read in each line of the file using the readline
method in a loop. This method returns a complete line including the newline character at
the end of the line. When an empty string is returned, it means that we have reached the
end of the file and we 'break' out of the loop.
By deafult, the print() function prints the text as well as an automatic newline to the
screen. We are suppressing the newline by specifying end='' because the line that is read
from the file already ends with a newline character. Then, we finally close the file.
Now, check the contents of the poem.txt file to confirm that the program has indeed
written and read from that file.
Pickle
Python provides a standard module called pickle using which you can store any Python
object in a file and then get it back later. This is called storing the object persistently.
Example:
#!/usr/bin/python
# Filename: pickling.py
import pickle
# the name of the file where we will store the object
shoplistfile = 'shoplist.data'
# the list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # destroy the shoplist variable
# Read back from the storagePython en:Input Output 93
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # load the object from the file
print(storedlist)
Output:
$ python pickling.py
['apple', 'mango', 'carrot']
How It Works:
To store an object in a file, we have to first open the file in 'w'rite 'b'inary mode and then
call the dump function of the pickle module. This process is called pickling.
Next, we retrieve the object using the load function of the pickle module which returns
the object. This process is called unpickling.
Summary
We have discussed various types of input/output and also file handling and using the pickle
module.
Next, we will explore the concept of exceptions.
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1583
Contributors: Horstjens, Swaroop, 1 anonymous edits
Python en:Exceptions
Introduction
Exceptions occur when certain exceptional situations occur in your program. For example,
what if you are going to read a file and the file does not exist? Or what if you accidentally
deleted it when the program was running? Such situations are handled using exceptions.
Similarly, what if your program had some invalid statements? This is handled by Python
which raises its hands and tells you there is an error.
Errors
Consider a simple print function call. What if we misspelt print as Print? Note the
capitalization. In this case, Python raises a syntax error.
>>> Print('Hello World')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
Print('Hello World')
NameError: name 'Print' is not defined
>>> print('Hello World')
Hello WorldPython en:Exceptions 94
Observe that a NameError is raised and also the location where the error was detected is
printed. This is what an error handler for this error does.
Exceptions
We will try to read input from the user. Press ctrl-d and see what happens.
>>> s = input('Enter something --> ')
Enter something -->
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
s = input('Enter something --> ')
EOFError: EOF when reading a line
Python raises an error called EOFError which basically means it found an end of file symbol
(which is represented by ctrl-d) when it did not expect to see it.
Handling Exceptions
We can handle exceptions using the try..except statement. We basically put our usual
statements within the try-block and put all our error handlers in the except-block.
#!/usr/bin/python
# Filename: try_except.py
try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {0}'.format(text))
Output:
$ python try_except.py
Enter something --> # Press ctrl-d
Why did you do an EOF on me?
$ python try_except.py
Enter something --> # Press ctrl-c
You cancelled the operation.
$ python try_except.py
Enter something --> no exceptions
You entered no exceptions
How It Works:
We put all the statements that might raise exceptions/errors inside the try block and then
put handlers for the appropriate errors/exceptions in the except clause/block. The exceptPython
en:Exceptions 95
clause can handle a single specified error or exception, or a parenthesized list of
errors/exceptions. If no names of errors or exceptions are supplied, it will handle all errors
and exceptions.
Note that there has to be at least one except clause associated with every try clause.
Otherwise, what's the point of having a try block?
If any error or exception is not handled, then the default Python handler is called which just
stops the execution of the program and prints an error message. We have already seen this
in action above.
You can also have an else clause associated with a try..except block. The else clause is
executed if no exception occurs.
In the next example, we will also see how to get the exception object so that we can retrieve
additional information.
Raising Exceptions
You can raise exceptions using the raise statement by providing the name of the
error/exception and the exception object that is to be thrown.
The error or exception that you can arise should be class which directly or indirectly must
be a derived class of the Exception class.
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
# Other work can continue as usual here
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print('ShortInputException: The input was {0} long, expected at
least {1}'\
.format(ex.length, ex.atleast))
else:
print('No exception was raised.')
Output:
$ python raising.py
Enter something --> aPython en:Exceptions 96
ShortInputException: The input was 1 long, expected at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
How It Works:
Here, we are creating our own exception type. This new exception type is called
ShortInputException. It has two fields - length which is the length of the given input, and
atleast which is the minimum length that the program was expecting.
In the except clause, we mention the class of error which will be stored as the variable
name to hold the corresponding error/exception object. This is analogous to parameters and
arguments in a function call. Within this particular except clause, we use the length and
atleast fields of the exception object to print an appropriate message to the user.
Try ..Finally
Suppose you are reading a file in your program. How do you ensure that the file object is
closed properly whether or not an exception was raised? This can be done using the
finally block. Note that you can use an except clause along with a finally block for the
same corresponding try block. You will have to embed one within another if you want to
use both.
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = open('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
print(line, end='')
time.sleep(2) # To make sure it runs for a while
except KeyboardInterrupt:
print('!! You cancelled the reading from the file.')
finally:
f.close()
print('(Cleaning up: Closed the file)')
Output:
$ python finally.py
Programming is fun
When the work is done
if you wanna make your work also fun:
!! You cancelled the reading from the file.Python en:Exceptions 97
(Cleaning up: Closed the file)
How It Works:
We do the usual file-reading stuff, but we have arbitrarily introduced sleeping for 2 seconds
after printing each line using the time.sleep function so that the program runs slowly
(Python is very fast by nature). When the program is still running, press ctrl-c to
interrupt/cancel the program.
Observe that the KeyboardInterrupt exception is thrown and the program quits. However,
before the program exits, the finally clause is executed and the file object is always closed.
The with statement
Acquiring a resource in the try block and subsequently releasing the resource in the
finally block is a common pattern. Hence, there is also a with statement that enables this
to be done in a clean manner:
#!/usr/bin/python
# Filename: using_with.py
with open("poem.txt") as f:
for line in f:
print(line, end='')
How It Works:
The output should be same as the previous example. The difference here is that we are
using the open function with the with statement - we leave the closing of the file to be
done automatically by with open.
What happens behind the scenes is that there is a protocol used by the with statement. It
fetches the object returned by the open statement, let's call it "thefile" in this case.
It always calls the thefile.__enter__ function before starting the block of code under it
and always calls thefile.__exit__ after finishing the block of code.
So the code that we would have written in a finally block is should be taken care of
automatically by the __exit__ method. This is what helps us to avoid having to use explicit
try..finally statements repeatedly.
More discussion on this topic is beyond scope of this book, so please refer PEP 343 (http://
www.python.org/dev/peps/pep-0343/) for comprehensive explanation.
Summary
We have discussed the usage of the try..except and try..finally statements. We have
seen how to create our own exception types and how to raise exceptions as well.
Next, we will explore the Python Standard Library.
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1470
Contributors: Swaroop, 2 anonymous editsPython en:Standard Library 98
Python en:Standard Library
Introduction
The Python Standard Library contains a huge number of useful modules and is part of every
standard Python installation. It is important to become familiar with the Python Standard
Library since many problems can be solved quickly if you are familiar with the range of
things that these libraries can do.
We will explore some of the commonly used modules in this library. You can find complete
details for all of the modules in the Python Standard Library in the 'Library Reference'
section (http://docs.python.org/dev/3.0/library/) of the documentation that comes with
your Python installation.
Let us explore a few useful modules.
Note
If you find the topics in this chapter too advanced, you may skip this chapter. However,
I highly recommend coming back to this chapter when you are more comfortable with
programming using Python.
sys module
The sys module contains system-specific functionality. We have already seen that the
sys.argv list contains the command-line arguments.
Suppose we want to check the version of the Python command being used so that, say, we
want to ensure that we are using at least version 3. The sys module gives us such
functionality.
>>> import sys
>>> sys.version_info
(3, 0, 0, 'beta', 2)
>>> sys.version_info[0] >= 3
True
How It Works:
The sys module has a version_info tuple that gives us the version information. The first
entry is the major version. We can check this to, for example, ensure the program runs only
under Python 3.0:
#!/usr/bin/python
# Filename: versioncheck.py
import sys, warnings
if sys.version_info[0] < 3:
warnings.warn("Need Python 3.0 for this program to run",
RuntimeWarning)
else:
print('Proceed as normal')
Output:Python en:Standard Library 99
$ python2.5 versioncheck.py
versioncheck.py:6: RuntimeWarning: Need Python 3.0 for this program
to run
RuntimeWarning)
$ python3 versioncheck.py
Proceed as normal
How It Works:
We use another module from the standard library called warnings that is used to display
warnings to the end-user. If the Python version number is not at least 3, we display a
corresponding warning.
logging module
What if you wanted to have some debugging messages or important messages to be stored
somewhere so that you can check whether your program has been running as you would
expect it? How do you "store somewhere" these messages? This can be achieved using the
logging module.
#!/usr/bin/python
# Filename: use_logging.py
import os, platform, logging
if platform.platform().startswith('Windows'):
logging_file = os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'), 'test.log')
else:
logging_file = os.path.join(os.getenv('HOME'), 'test.log')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s : %(levelname)s : %(message)s',
filename = logging_file,
filemode = 'w',
)
logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")
Output:
$python use_logging.py
Logging to C:\Users\swaroop\test.log
If we check the contents of test.log, it will look something like this:
2008-09-03 13:18:16,233 : DEBUG : Start of the program
2008-09-03 13:18:16,233 : INFO : Doing something
2008-09-03 13:18:16,233 : WARNING : Dying nowPython en:Standard Library 100
How It Works:
We use three modules from the standard library - the os module for interacting with the
operating system, the platform module for information about the platform i.e. the
operating system and the logging module to log information.
First, we check which operating system we are using by checking the string returned by
platform.platform() (for more information, see import platform; help(platform)). If it
is Windows, we figure out the home drive, the home folder and the filename where we want
to store the information. Putting these three parts together, we get the full location of the
file. For other platforms, we need to know just the home folder of the user and we get the
full location of the file.
We use the os.path.join() function to put these three parts of the location together. The
reason to use a special function rather than just adding the strings together is because this
function will ensure the full location matches the format expected by the operating system.
We configure the logging module to write all the messages in a particular format to the
file we have specified.
Finally, we can put messages that are either meant for debugging, information, warning or
even critical messages. Once the program has run, we can check this file and we will know
what happened in the program, even though no information was displayed to the user
running the program.
urllib and json modules
How much fun would it be if we could write our own program that will get search results
from the web? Let us explore that now.
This can be achieved using a few modules. First is the urllib module that we can use to
fetch any webpage from the internet. We will make use of Yahoo! Search to get the search
results and luckily they can give us the results in a format called JSON which is easy for us
to parse because of the built-in json module in the standard library.
TODO
This program doesn't work yet which seems to be a bug in Python 3.0 beta 2 (http:/ /
bugs.python.org/issue3763).
#!/usr/bin/python
# Filename: yahoo_search.py
import sys
if sys.version_info[0] != 3:
sys.exit('This program needs Python 3.0')
import json
import urllib, urllib.parse, urllib.request, urllib.response
# Get your own APP ID at http://developer.yahoo.com/wsregapp/
YAHOO_APP_ID =
'jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8.lBSfPhwr'
SEARCH_BASE =
'http://search.yahooapis.com/WebSearchService/V1/webSearch'Python en:Standard Library 101
class YahooSearchError(Exception):
pass
# Taken from http://developer.yahoo.com/python/python-json.html
def search(query, results=20, start=1, **kwargs):
kwargs.update({
'appid': YAHOO_APP_ID,
'query': query,
'results': results,
'start': start,
'output': 'json'
})
url = SEARCH_BASE + '?' + urllib.parse.urlencode(kwargs)
result = json.load(urllib.request.urlopen(url))
if 'Error' in result:
raise YahooSearchError(result['Error'])
return result['ResultSet']
query = input('What do you want to search for? ')
for result in search(query)['Result']:
print("{0} : {1}".format(result['Title'], result['Url']))
Output:
TODO
How It Works:
We can get the search results from a particular website by giving the text we are searching
for in a particular format. We have to specify many options which we combine using
key1=value1&key2=value2 format which is handled by the urllib.parse.urlencode()
function.
So for example, open this link in your web browser (http:/ / search. yahooapis. com/
WebSearchService/ V1/ webSearch?query=byte+ of+ python&
appid=jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8. lBSfPhwr&
results=20& start=1& output=json) and you will see 20 results, starting from the first
result, for the words "byte of python", and we are asking for the output in JSON format.
We make a connection to this URL using the urllib.request.urlopen() function and pass
that file handle to json.load() which will read the content and simultaneously convert it
to a Python object. We then loop through these results and display it to the end-user.Python
en:Standard Library 102
Module of the Week Series
There is much more to be explored in the standard library such as debugging (http://docs.
python. org/dev/ library/pdb.html), handling command line options (http:/ /docs.python.
org/dev/3.0/ library/getopt.html), regular expressions (http:/ /www.diveintopython.org/
regular_expressions/index.html) and so on.
The best way to further explore the standard library is to read Doug Hellmann's excellent
Python Module of the Week (http://www.doughellmann.com/projects/PyMOTW/) series.
Summary
We have explored some of the functionality of many modules in the Python Standard
Library. It is highly recommended to browse through the Python Standard Library
documentation (http:/ / docs. python. org/ dev/ 3. 0/ library/ ) to get an idea of all the
modules that are available.
Next, we will cover various aspects of Python that will make our tour of Python more
complete.
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1156
Contributors: Swaroop, 2 anonymous edits
Python en:More
Introduction
So far we have covered majority of the various aspects of Python that you will use. In this
chapter, we will cover some more aspects that will make our knowledge of Python more
well-rounded.
Passing tuples around
Ever wished you could return two different values from a function? You can. All you have to
do is use a tuple.
>>> def get_error_details():
... return (2, 'second error details')
...
>>> errnum, errstr = get_error_details()
>>> errnum
2
>>> errstr
'second error details'
Notice that the usage of a, b = <some expression> interprets the result of the expression
as a tuple with two values.
If you want to interpret the results as (a, <everything else>), then you just need to star
it just like you would in function parameters:Python en:More 103
>>> a, *b = [1, 2, 3, 4]
>>> a
1
>>> b
[2, 3, 4]
This also means the fastest way to swap two variables in Python is:
>>> a = 5; b = 8
>>> a, b = b, a
>>> a, b
(8, 5)
Special Methods
There are certain methods such as the __init__ and __del__ methods which have special
significance in classes.
Special methods are used to mimic certain behaviors of built-in types. For example, if you
want to use the x[key] indexing operation for your class (just like you use it for lists and
tuples), then all you have to do is implement the __getitem__() method and your job is
done. If you think about it, this is what Python does for the list class itself!
Some useful special methods are listed in the following table. If you want to know about all
the special methods, see the manual (http:/ / docs. python. org/ dev/ 3. 0/ reference/
datamodel.html#special-method-names).
Name Explanation
__init__(self, ...) This method is called just before the newly created object is returned for
usage.
__del__(self) Called just before the object is destroyed
__str__(self) Called when we use the print function or when str() is used.
__lt__(self, other) Called when the less than operator (<) is used. Similarly, there are special
methods for all the operators (+, >, etc.)
__getitem__(self, key) Called when x[key] indexing operation is used.
__len__(self) Called when the built-in len() function is used for the sequence object.
Single Statement Blocks
We have seen that each block of statements is set apart from the rest by its own indentation
level. Well, there is one caveat. If your block of statements contains only one single
statement, then you can specify it on the same line of, say, a conditional statement or
looping statement. The following example should make this clear:
>>> flag = True
>>> if flag: print 'Yes'
...
Yes
Notice that the single statement is used in-place and not as a separate block. Although, you
can use this for making your program smaller, I strongly recommend avoiding this short-cut
method, except for error checking, mainly because it will be much easier to add an extraPython
en:More 104
statement if you are using proper indentation.
Lambda Forms
A lambda statement is used to create new function objects and then return them at
runtime.
#!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print(twice('word'))
print(twice(5))
Output:
$ python lambda.py
wordword
10
How It Works:
Here, we use a function make_repeater to create new function objects at runtime and
return it. A lambda statement is used to create the function object. Essentially, the lambda
takes a parameter followed by a single expression only which becomes the body of the
function and the value of this expression is returned by the new function. Note that even a
print statement cannot be used inside a lambda form, only expressions.
TODO
Can we do a list.sort() by providing a compare function created using lambda?
points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
# points.sort(lambda a, b : cmp(a['x'], b['x']))
List Comprehension
List comprehensions are used to derive a new list from an existing list. Suppose you have a
list of numbers and you want to get a corresponding list with all the numbers multiplied by
2 only when the number itself is greater than 2. List comprehensions are ideal for such
situations.
#!/usr/bin/python
# Filename: list_comprehension.py
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)
Output:Python en:More 105
$ python list_comprehension.py
[6, 8]
How It Works:
Here, we derive a new list by specifying the manipulation to be done (2*i) when some
condition is satisfied (if i > 2). Note that the original list remains unmodified.
The advantage of using list comprehensions is that it reduces the amount of boilerplate
code required when we use loops to process each element of a list and store it in a new list.
Receiving Tuples and Lists in Functions
There is a special way of receiving parameters to a function as a tuple or a dictionary using
the * or ** prefix respectively. This is useful when taking variable number of arguments in
the function.
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
Because we have a * prefix on the args variable, all extra arguments passed to the
function are stored in args as a tuple. If a ** prefix had been used instead, the extra
parameters would be considered to be key/value pairs of a dictionary.
exec and eval
The exec function is used to execute Python statements which are stored in a string or file,
as opposed to written in the program itself. For example, we can generate a string
containing Python code at runtime and then execute these statements using the exec
statement:
>>> exec('print("Hello World")')
Hello World
Similarly, the eval function is used to evaluate valid Python expressions which are stored
in a string. A simple example is shown below.
>>> eval('2*3')
6Python en:More 106
The assert statement
The assert statement is used to assert that something is true. For example, if you are very
sure that you will have at least one element in a list you are using and want to check this,
and raise an error if it is not true, then assert statement is ideal in this situation. When
the assert statement fails, an AssertionError is raised.
>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> mylist
[]
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
The assert statement should be used judiciously. Most of the time, it is better to catch
exceptions, either handle the problem or display an error message to the user and then
quit.
The repr function
The repr function is used to obtain a canonical string representation of the object. The
interesting part is that you will have eval(repr(object)) == object most of the time.
>>> i = []
>>> i.append('item')
>>> repr(i)
"['item']"
>>> eval(repr(i))
['item']
>>> eval(repr(i)) == i
True
Basically, the repr function is used to obtain a printable representation of the object. You
can control what your classes return for the repr function by defining the __repr__
method in your class.
Summary
We have covered some more features of Python in this chapter and yet we haven't covered
all the features of Python. However, at this stage, we have covered most of what you are
ever going to use in practice. This is sufficient for you to get started with whatever
programs you are going to create.
Next, we will discuss how to explore Python further.Python en:More 107
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1463
Contributors: Swaroop, 1 anonymous edits
Python en:What Next
If you have read this book thoroughly till now and practiced writing a lot of programs, then
you must have become comfortable and familiar with Python. You have probably created
some Python programs to try out stuff and to exercise your Python skills as well. If you have
not done it already, you should. The question now is 'What Next?'.
I would suggest that you tackle this problem:
Create your own command-line address-book program using which you can
browse, add, modify, delete or search for your contacts such as friends, family
and colleagues and their information such as email address and/or phone number.
Details must be stored for later retrieval.
This is fairly easy if you think about it in terms of all the various stuff that we have come
across till now. If you still want directions on how to proceed, then here's a hint.
Hint (Don't read)
Create a class to represent the person's information. Use a dictionary to store person
objects with their name as the key. Use the pickle module to store the objects
persistently on your hard disk. Use the dictionary built-in methods to add, delete and
modify the persons.
Once you are able to do this, you can claim to be a Python programmer. Now, immediately
send me a mail (http://www.swaroopch.com/contact/) thanking me for this great book ;-)
. This step is optional but recommended. Also, please consider making a donation,
contributing improvements or volunteering translations to support the continued
development of this book.
If you found that program easy, here's another one:
Implement the replace command (http:/ / unixhelp. ed. ac. uk/ CGI/
man-cgi?replace). This command will replace one string with another in the list of
files provided.
The replace command can be as simple or as sophisticated as you wish, from simple string
substitution to looking for patterns (regular expressions).
After that, here are some ways to continue your journey with Python:Python en:What Next 108
Example Code
The best way to learn a programming language is to write a lot of code and read a lot of
code:
• The PLEAC project (http://pleac.sourceforge.net/pleac_python/index.html)
• Rosetta code repository (http://www.rosettacode.org/wiki/Category:Python)
• Python examples at java2s (http://www.java2s.com/Code/Python/CatalogPython.htm)
• Python Cookbook (http://code.activestate.com/recipes/langs/python/) is an
extremely valuable collection of recipes or tips on how to solve certain kinds of problems
using Python. This is a must-read for every Python user.
Questions and Answers
• Official Python Dos and Don'ts (http://docs.python.org/dev/howto/doanddont.html)
• Official Python FAQ (http://www.python.org/doc/faq/general/)
• Norvig's list of Infrequently Asked Questions (http://norvig.com/python-iaq.html)
• Python Interview Q & A (http://dev.fyicenter.com/Interview-Questions/Python/index.
html)
• StackOverflow questions tagged with python (http://beta.stackoverflow.com/
questions/tagged/python)
Tips and Tricks
• Python Tips & Tricks (http://www.siafoo.net/article/52)
• Advanced Software Carpentry using Python (http://ivory.idyll.org/articles/
advanced-swc/)
• Charming Python (http://gnosis.cx/publish/tech_index_cp.html) is an excellent series
of Python-related articles by David Mertz.
Books, Papers, Tutorials, Videos
The logical next step after this book is to read Mark Pilgrim's awesome Dive Into Python
(http:/ / www. diveintopython. org) book which you can read fully online as well. The Dive
Into Python book explores topics such as regular expressions, XML processing, web
services, unit testing, etc. in detail.
Other useful resources are:
• ShowMeDo videos for Python (http://showmedo.com/videos/python)
• GoogleTechTalks videos on Python (http://youtube.com/
results?search_query=googletechtalks+python)
• Awaretek's comprehensive list of Python tutorials (http://www.awaretek.com/tutorials.
html)
• The Effbot's Python Zone (http://effbot.org/zone/)
• Links at the end of every Python-URL! email (http://groups.google.com/group/comp.
lang.python.announce/t/37de95ef0326293d)
• Python Papers (http://pythonpapers.org)Python en:What Next 109
Discussion
If you are stuck with a Python problem, and don't know whom to ask, then the
comp.lang.python discussion group (http://groups.google.com/group/comp.lang.python/
topics) is the best place to ask your question.
Make sure you do your homework and have tried solving the problem yourself first.
News
If you want to learn what is the latest in the world of Python, then follow the Official Python
Planet (http:/ / planet. python. org) and/or the Unofficial Python Planet (http:/ / www.
planetpython.org).
Installing libraries
There are a huge number of open source libraries at the Python Package Index (http:/ /
pypi.python.org/pypi) which you can use in your own programs.
To install and use these libraries, you can use Philip J. Eby's excellent EasyInstall tool
(http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install).
Graphical Software
Suppose you want to create your own graphical programs using Python. This can be done
using a GUI (Graphical User Interface) library with their Python bindings. Bindings are
what allow you to write programs in Python and use the libraries which are themselves
written in C or C++ or other languages.
There are lots of choices for GUI using Python:
PyQt
This is the Python binding for the Qt toolkit which is the foundation upon which the
KDE is built. Qt is extremely easy to use and very powerful especially due to the Qt
Designer and the amazing Qt documentation. PyQt is free if you want to create open
source (GPL'ed) software and you need to buy it if you want to create proprietary
closed source software. Starting with Qt 4.5 you can use it to create non-GPL software
as well. To get started, read the PyQt tutorial (http:/ /zetcode.com/tutorials/pyqt4/)
or the PyQt book (http://www.qtrac.eu/pyqtbook.html).
PyGTK
This is the Python binding for the GTK+ toolkit which is the foundation upon which
GNOME is built. GTK+ has many quirks in usage but once you become comfortable,
you can create GUI apps fast. The Glade graphical interface designer is indispensable.
The documentation is yet to improve. GTK+ works well on Linux but its port to
Windows is incomplete. You can create both free as well as proprietary software using
GTK+. To get started, read the PyGTK tutorial (http://www.pygtk.org/tutorial.html).
wxPython
This is the Python bindings for the wxWidgets toolkit. wxPython has a learning curve
associated with it. However, it is very portable and runs on Linux, Windows, Mac and
even embedded platforms. There are many IDEs available for wxPython which include
GUI designers as well such as SPE (Stani's Python Editor) (http://spe.pycs.net/) andPython
en:What Next 110
the wxGlade (http:/ /wxglade. sourceforge. net/ ) GUI builder. You can create free as
well as proprietary software using wxPython. To get started, read the wxPython
tutorial (http://zetcode.com/wxpython/).
TkInter
This is one of the oldest GUI toolkits in existence. If you have used IDLE, you have
seen a TkInter program at work. It doesn't have one of the best look & feel because it
has an old-school look to it. TkInter is portable and works on both Linux/Unix as well
as Windows. Importantly, TkInter is part of the standard Python distribution. To get
started, read the Tkinter tutorial (http:/ / www. pythonware. com/ library/ tkinter/
introduction/).
For more choices, see the GuiProgramming wiki page at the official python website (http://
www.python.org/cgi-bin/moinmoin/GuiProgramming).
Summary of GUI Tools
Unfortunately, there is no one standard GUI tool for Python. I suggest that you choose one
of the above tools depending on your situation. The first factor is whether you are willing to
pay to use any of the GUI tools. The second factor is whether you want the program to run
only on Windows or on Mac and Linux or all of them. The third factor, if Linux is a chosen
platform, is whether you are a KDE or GNOME user on Linux.
For a more detailed and comprehensive analysis, see Page 26 of the The Python Papers,
Volume 3, Issue 1 (http://archive.pythonpapers.org/ThePythonPapersVolume3Issue1.pdf).
Various Implementations
There are usually two parts a programming language - the language and the software. A
language is how you write something. The software is what actually runs our programs.
We have been using the CPython software to run our programs. It is referred to as CPython
because it is written in the C language and is the Classical Python interpreter.
There are also other software that can run your Python programs:
Jython (http://www.jython.org)
A Python implementation that runs on the Java platform. This means you can use Java
libraries and classes from within Python language and vice-versa.
IronPython (http:/ / www. codeplex. com/ Wiki/ View.
aspx?ProjectName=IronPython)
A Python implementation that runs on the .NET platform. This means you can use
.NET libraries and classes from within Python language and vice-versa.
PyPy (http://codespeak.net/pypy/dist/pypy/doc/home.html)
A Python implementation written in Python! This is a research project to make it fast
and easy to improve the interpreter since the interpreter itself is written in a dynamic
language (as opposed to static languages such as C, Java or C# in the above three
implementations)
Stackless Python (http://www.stackless.com)
A Python implementation that is specialized for thread-based performance.Python en:What Next
111
There are also others such as CLPython (http:/ / common-lisp. net/ project/ clpython/ ) - a
Python implementation written in Common Lisp and IronMonkey (http:/ /wiki.mozilla.org/
Tamarin:IronMonkey) which is a port of IronPython to work on top of a JavaScript
interpreter which could mean that you can use Python (instead of JavaScript) to write your
web-browser ("Ajax") programs.
Each of these implementations have their specialized areas where they are useful.
Summary
We have now come to the end of this book but, as they say, this is the the beginning of the
end!. You are now an avid Python user and you are no doubt ready to solve many problems
using Python. You can start automating your computer to do all kinds of previously
unimaginable things or write your own games and much much more. So, get started!
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1845
Contributors: Swaroop, 2 anonymous edits
Python en:Appendix FLOSS
Free/Libre and Open Source Software (FLOSS)
FLOSS (http:/ / en. wikipedia. org/ wiki/ FLOSS) is based on the concept of a community,
which itself is based on the concept of sharing, and particularly the sharing of knowledge.
FLOSS are free for usage, modification and redistribution.
If you have already read this book, then you are already familiar with FLOSS since you have
been using Python all along and Python is an open source software!
Here are some examples of FLOSS to give an idea of the kind of things that community
sharing and building can create:
• Linux. This is a FLOSS operating system that the whole world is slowly embracing! It
was started by Linus Torvalds as a student. Now, it is giving competition to Microsoft
Windows. [ Linux Kernel (http://www.kernel.org) ]
• Ubuntu. This is a community-driven distribution, sponsored by Canonical and it is the
most popular Linux distribution today. It allows you to install a plethora of FLOSS
available and all this in an easy-to-use and easy-to-install manner. Best of all, you can just
reboot your computer and run Linux off the CD! This allows you to completely try out the
new OS before installing it on your computer. [ Ubuntu Linux (http://www.ubuntu.
com) ]
• OpenOffice.org. This is an excellent office suite with a writer, presentation,
spreadsheet and drawing components among other things. It can even open and edit MS
Word and MS PowerPoint files with ease. It runs on almost all platforms. [ OpenOffice
(http://www.openoffice.org) ]
• Mozilla Firefox. This is the next generation web browser which is giving great
competition to Internet Explorer. It is blazingly fast and has gained critical acclaim for its
sensible and impressive features. The extensions concept allows any kind of plugins to be
used.Python en:Appendix FLOSS 112
• Its companion product Thunderbird is an excellent email client that makes reading email
a snap. [ Mozilla Firefox (http://www.mozilla.org/products/firefox), Mozilla
Thunderbird (http://www.mozilla.org/products/thunderbird) ]
• Mono. This is an open source implementation of the Microsoft .NET platform. It allows
.NET applications to be created and run on Linux, Windows, FreeBSD, Mac OS and many
other platforms as well. [ Mono (http://www.mono-project.com), ECMA (http://www.
ecma-international.org), Microsoft .NET (http://www.microsoft.com/net) ]
• Apache web server. This is the popular open source web server. In fact, it is the most
popular web server on the planet! It runs nearly more than half of the websites out there.
Yes, that's right - Apache handles more websites than all the competition (including
Microsoft IIS) combined. [ Apache (http://httpd.apache.org) ]
• MySQL. This is an extremely popular open source database server. It is most famous for
it's blazing speed. It is the M in the famous LAMP stack which runs most of the websites
on the internet. [ MySQL (http://www.mysql.com) ]
• VLC Player. This is a video player that can play anything from DivX to MP3 to Ogg to
VCDs and DVDs to ... who says open source ain't fun? ;-) [ VLC media player (http://
www.videolan.org/vlc/) ]
• GeexBox is a Linux distribution that is designed to play movies as soon as you boot up
from the CD! [ GeexBox (http://geexbox.org/en/start.html) ]
This list is just intended to give you a brief idea - there are many more excellent FLOSS out
there, such as the Perl language, PHP language, Drupal content management system for
websites, PostgreSQL database server, TORCS racing game, KDevelop IDE, Xine - the
movie player, VIM editor, Quanta+ editor, Banshee audio player, GIMP image editing
program, ... This list could go on forever.
To get the latest buzz in the FLOSS world, check out the following websites:
• linux.com (http://www.linux.com)
• LinuxToday (http://www.linuxtoday.com)
• NewsForge (http://www.newsforge.com)
• DistroWatch (http://www.distrowatch.com)
Visit the following websites for more information on FLOSS:
• SourceForge (http://www.sourceforge.net)
• FreshMeat (http://www.freshmeat.net)
So, go ahead and explore the vast, free and open world of FLOSS!
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=1580
Contributors: Swaroop, 1 anonymous editsPython en:Appendix About 113
Python en:Appendix About
Colophon
Almost all of the software that I have used in the creation of this book are free and open
source software.
Birth of the Book
In the first draft of this book, I had used Red Hat 9.0 Linux as the foundation of my setup
and in the sixth draft, I used Fedora Core 3 Linux as the basis of my setup.
Initially, I was using KWord to write the book (as explained in the History Lesson in the
preface).
Teenage Years
Later, I switched to DocBook XML using Kate but I found it too tedious. So, I switched to
OpenOffice which was just excellent with the level of control it provided for formatting as
well as the PDF generation, but it produced very sloppy HTML from the document.
Finally, I discovered XEmacs and I rewrote the book from scratch in DocBook XML (again)
after I decided that this format was the long term solution.
In the sixth draft, I decided to use Quanta+ to do all the editing. The standard XSL
stylesheets that came with Fedora Core 3 Linux were being used. The standard default
fonts are used as well. The standard fonts are used as well. However, I had written a CSS
document to give color and style to the HTML pages. I had also written a crude lexical
analyzer, in Python of course, which automatically provides syntax highlighting to all the
program listings.
Now
For this seventh draft, I'm using MediaWiki (http://www.mediawiki.org) as the basis of my
setup (http://www.swaroopch.com/notes/). Now I edit everything online and the readers
can directly read/edit/discuss within the wiki website.
I still use Vim for editing thanks to the ViewSourceWith extension for Firefox (https:/ /
addons.mozilla.org/en-US/firefox/addon/394) that integrates with Vim.Python en:Appendix
About 114
About The Author
http://www.swaroopch.com/about/
Previous Next
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=236
Contributors: Swaroop
Python en:Appendix Revision History
• 1.90
• 04/09/2008 and still in progress
• Revival after a gap of 3.5 years!
• Updating to Python 3.0
• Rewrite using MediaWiki (again)
• 1.20
• 13/01/2005
• Complete rewrite using Quanta+ on FC3 with lot of corrections and updates. Many
new examples. Rewrote my DocBook setup from scratch.
• 1.15
• 28/03/2004
• Minor revisions
• 1.12
• 16/03/2004
• Additions and corrections.
• 1.10
• 09/03/2004
• More typo corrections, thanks to many enthusiastic and helpful readers.
• 1.00
• 08/03/2004
• After tremendous feedback and suggestions from readers, I have made significant
revisions to the content along with typo corrections.
• 0.99
• 22/02/2004
• Added a new chapter on modules. Added details about variable number of arguments
in functions.
• 0.98
• 16/02/2004
• Wrote a Python script and CSS stylesheet to improve XHTML output, including a
crude-yet-functional lexical analyzer for automatic VIM-like syntax highlighting of the
program listings.
• 0.97
• 13/02/2004
• Another completely rewritten draft, in DocBook XML (again). Book has improved a lot
- it is more coherent and readable.Python en:Appendix Revision History 115
• 0.93
• 25/01/2004
• Added IDLE talk and more Windows-specific stuff
• 0.92
• 05/01/2004
• Changes to few examples.
• 0.91
• 30/12/2003
• Corrected typos. Improvised many topics.
• 0.90
• 18/12/2003
• Added 2 more chapters. OpenOffice format with revisions.
• 0.60
• 21/11/2003
• Fully rewritten and expanded.
• 0.20
• 20/11/2003
• Corrected some typos and errors.
• 0.15
• 20/11/2003
• Converted to DocBook XML.
• 0.10
• 14/11/2003
• Initial draft using KWord.
→ Previous → Back to Table of Contents
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=240
Contributors: SwaroopPython en:Appendix Changes for Python 3000 116
Python en:Appendix Changes for
Python 3000
• Vim and Emacs editors
• http://henry.precheur.org/2008/4/18/Indenting%20Python%20with%20VIM.html
• http://www.enigmacurry.com/2008/05/09/emacs-as-a-powerful-python-ide/
• String - unicode only
• http://docs.python.org/dev/3.0/tutorial/introduction.html#about-unicode
• Non-ASCII identifiers allowed
• http://www.python.org/dev/peps/pep-3131/
• print() function
• http://www.python.org/dev/peps/pep-3105/
• raw_input() becomes input()
• http://www.python.org/dev/peps/pep-3111/
• Integer Literal Support and Syntax
• http://www.python.org/dev/peps/pep-3127/
• nonlocal statement
• http://www.python.org/dev/peps/pep-3104/
• Functions can take * argument (varargs) for lists and keyword-only arguments
• http://www.python.org/dev/peps/pep-3102/
• Functions can have annotations (make a passing note?)
• http://www.python.org/dev/peps/pep-3107/
• Better explanation of modules, packages and their organization (including __init__.py,
etc.)
• http://ivory.idyll.org/articles/advanced-swc/#packages
• String .format() instead of % operator
• http://www.python.org/dev/peps/pep-3101/
• http://docs.python.org/dev/library/string.html#formatstrings
• Dict method changes
• http://www.python.org/dev/peps/pep-3106/
• Built-in set class, in data structures chapter
• Problem Solving
• Use http://gnuwin32.sourceforge.net/packages/zip.htm on Windows
• Classes
• http://docs.python.org/dev/3.0/reference/datamodel.html
• Metaclasses
• http://www.python.org/dev/peps/pep-3115/
• Abstract Base Classes
• http://www.python.org/dev/peps/pep-3119/
• Not sure if any changes required for New I/O
• http://www.python.org/dev/peps/pep-3116/
• Exception handlingPython en:Appendix Changes for Python 3000 117
• http://www.python.org/dev/peps/pep-0352/
• http://www.python.org/dev/peps/pep-3109/
• http://www.python.org/dev/peps/pep-3110/
• Standard Library - interesting additions
• Reorganization : http://www.python.org/dev/peps/pep-3108/
• http://docs.python.org/dev/library/warnings.html
• http://docs.python.org/dev/library/logging.html (important)
• http://docs.python.org/dev/library/urllib.html
• http://docs.python.org/dev/library/json.html
• Debugging
• http://docs.python.org/dev/library/pdb.html
• http://docs.python.org/dev/3.0/library/trace.html
• eval, repr/ascii functions
• getopt/optparse - how to write a standard command-line program using python?
• something like replace?
• http://hpux.connect.org.uk/hppd/hpux/Users/replace-2.24/man.html
• More
• Unpacking can take * argument
• http://www.python.org/dev/peps/pep-3132/
• with statement
• http://www.python.org/dev/peps/pep-0343/
• What Next?
• Implement 'replace'
• http://unixhelp.ed.ac.uk/CGI/man-cgi?replace
• Mention use of PyPI
• Q&A
• http://docs.python.org/dev/howto/doanddont.html
• http://www.python.org/doc/faq/general/
• http://norvig.com/python-iaq.html
• Books & Resources
• http://www.coderholic.com/free-python-programming-books/
• http://pythonpapers.org
• http://www.mobilepythonbook.org
• http://effbot.org/zone/
• Links at the end of every Python-URL! email
• http://groups.google.com/group/comp.lang.python.announce/t/
37de95ef0326293d
• Examples
• http://www.rosettacode.org
• http://dev.fyicenter.com/Interview-Questions/Python/index.html
• http://www.java2s.com/Code/Python/CatalogPython.htm
• Tips & Tricks
• http://www.siafoo.net/article/52
Source: http://www.swaroopch.com/mediawiki/index.php?oldid=242Python en:Appendix
Changes for Python 3000 118
Contributors: Swaroop
License
Creative Commons Attribution-Share Alike 3.0 Unported
http://creativecommons.org/licenses/by-sa/3.0/