Things that got lost on the way

From Training Material
Jump to navigation Jump to search


Getting help inside Python

The documentation for each function and module can be shown by the help() function. dir()gives a list of functions in a module.

import time
print help(time.asctime)
print dir(time)

Comparing things

The cmp() function allows to compare two elements of the same type. This is useful for sorting. cmp() returns -1, 0, or 1.

a = 45
b = 32
print cmp( a, b )

Namespaces in Python

Each module and function in Python has its own set of variables and function names. Therefore, it is no problem to use the same names in different locations. They will not interfere.

What None is good for

The None variable type is used when a function does not have a return statement. You can also use it to indicate that some position in a list or dictionary is empty:

traffic_light = [None, None, 'green']

Deleting variables

Python can 'forget' a variable, whatever it contains:

a = 100
del(a)
print a # error

This can be also used to delete items from a dictionary:

d = {1:'A', 2:'B'}
del(d[1])
print d