Interactive/Python GUI shell$ python3
Editing a new program: File -> New Window / Type program / File -> Save As... / Run -> Run Module
Getting help on keywords, commands, module names, function names>>> help
Type help() for interactive help, or help(object) for help about object.
...displays my_func docstring
Case sensitivityAll names in Python are case-sensitive: variable names, function names, class names, module names, exception names.
Code blocksAre defined by indentation, which may be consistent, that is code blocks can contain multiple lines, as long as they are all indented the same amount. How many spaces to indent, you choose (e.g. four). Blank lines don’t count as code block delimiters. Carriage returns are used to separate statements (instead of C semicolons) and a colon and indentation to separate code blocks (instead of C curly braces).
ObjectsEverything is an object: functions, modules, strings, lists, class, class instances. And everything can have attributes and methods, it can be assigned to a variable or passed as an argument to a function. Not all objects are subclassable.
Strings'''A multi-line string is delimited by triple quotes and
can include carriage returns and quote chars (", ')
Often used to avoid escaping those chars too'''
Functionsdef func_name(argument_1, ..., named_arg1=default_value_1, ...):
'''... optional documentation string... Must be the first line.
It is a multi-line string.'''
Without a return statement, every functions returns None, the Python null value.
Return the docstring as one of the function built-in attributes:
ModulesImport the module_name program as a module:
>>> import module_name
sys.path is a list of directory names that constitute the current library search path (not used when importing built-in modules):
>>> import sys
['', '/usr/lib/python3.2', '/usr/lib/python3.2/plat-linux2', '/usr/lib/python3.2/lib-dynload', '/usr/local/lib/python3.2/dist-packages', '/usr/lib/python3/dist-packages']
Insert a new directory as the first item of the sys.path list:
>>> sys.path.insert(0, "new_path")
ExceptionsFunctions don’t declare which exceptions they might raise, that must be determined by code inspection.
You don’t need to handle an exception in the function that raises it. If one function doesn’t handle it, the exception is passed to the calling function, then that function’s calling function, and so on “up the stack.” If the exception is never handled, your program will crash, Python will print a “traceback” to standard error (it may be what you want).
Generate an exception:
Exceptions are implemented as classes: a
raisestatement is actually creating an instance of the
exceptionclass and passing the string
to its initialization method.
Handle an exception:
Some bulti-in exceptions:
ImportError: Raised when you try to import a module and fail, e.g. the module doesn’t exist in sys.path.
NameError: unbound variable referenced (a variable that has never been assigned a value)