http://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Python1_Basics.html
- Expression in parentheses
()
, square bracket[]
, and curly braces{}
can span multiple lines. - A backslash (
\
) at the end of the line denotes continuation to the next line. This is an old rule and is NOT recommended as it is error-prone.
A compound statement, such as def
(function definition), while
-loop, begins with a header line terminated with a colon (:
); followed by the indented body block. Python does not specify how much indentation to use, but all statements of the body block must start at the same distance from the right margin.
In Python, 0
, None
and empty value (such as empty string ''
, ""
, empty list []
, empty tuple ()
, empty dictionary {}
) are treated as False
; anything else are treated as True
. Booleans can also act as integers in arithmetic operations with 1
for True
and 0
for False
.
Python is dynamic typed. It associates types with objects, instead of variables. That is, a variable does not have a fixed type and can be assigned an object of any type. A variable simply provides a reference to an object.
You do not need to declare a variable. A variable is created automatically when a value is first assigned, which link the variable to the object. You can use built-in function type(var_name)
to get the object type referenced by a variable.
Python does not support increment (++
) and decrement (--
) operators (as in C/C++/Java). You need to use i = i + 1
or i += 1
for increment.
import module_name
statement: To refer to an attribute, use module_name.attr_name
.
from module_name import attr_name
statement: You can use attr_name
directly without the module_name
.
from module_name import *
statement: Import all attributes of the module.
To place a single quote ('
) inside a single-quoted string, you need to use escape sequence \'
. Similarly, to place a double quote ("
) inside a double-quoted string, use \"
. There is no need for escape sequence to place a single quote inside a double-quoted string; or double quote inside a single-quoted string.
Strings are immutable, i.e., their contents cannot be modified. String functions such as upper()
, replace()
returns a new string object instead of modifying the existing object.
Tuples are similar to list except that they are immutable (like string). A tuple is enclosed in parentheses ()
.
Python's built-in dictionary type supports key-value pairs (or name-value pairs, or associative array, or mapping) implemented using hash tables.
- Dictionary is enclosed by curly braces
{}
. The name and value are separated by a colon (:
). - Unlike list (or array), which indexes element using a integral index (0, 1, 2, 3,...), dictionary can be indexed using number, string or other types as the key.
- Names created inside a function (i.e. within
def
statement) are local to the function and are visible inside the function only. - Names created outside all functions (all
def
s) are global to that particular file (but not the other files). They are visible inside all functiondef
. Global-scope in Python is equivalent to file-scope. There is no all-file-scope in Python. - If you assign a value to a name inside the function
def
, a local name is created, which will hide the global name. - To modify a global name, you need to use
global
statement to declare the name global - For nested functions (or lambda function), you can use the
nonlocal
statement in the inner function to reference names in the enclosing outer function. - You can use
del
statement to remove names from the namespace,
In Python:
- Immutable argument (such as integers, floats, numbers, strings and tuples) are passed by value.
- Mutable argument (such as lists, dictionaries, sets and instances of classes) are passed by reference, which can be modified inside the function.
You can use *
to pack all the remaining arguments into a tuple. For example,
def compute_sum(a, *b): """ Function with arbitrary argument """ print(a, b) return a + sum(b) print(compute_sum(1)) # b is () print(compute_sum(1, 2)) # b is (2,) print(compute_sum(1, 2, 3)) # b is (2, 3) print(compute_sum(1, 2, 3, 4)) # b is (2, 3, 4)
Lambda functions are anonymous function or unamed function. They are used to inline a function definition, or to defer execution of certain codes. The syntax is:
lambda arg1, arg2, ...: statements
For example,
>>> f1 = lambda a, b, c: a + b + c >>> f1(1, 2, 3) 6 >>> f2 = lambda a, b=2, c=3: a + b + c >>> f2(1, 2, 3) 6 >>> f2(8) 13
In Python, you can asssing a function to a variable.
You can issue these commands to get information about the module:
>>> help(greet)
>>> greet.__doc__ # documentation string
A Python module is a file containing Python codes. The module name is the filename without the extension ".py
". That is, module shall be saved as "moduel_name.py
". A module typically begins with a documentation string (docstring), which is delimiter by triple quotes to permit multi-line description and can be retrieved via attribute module_name.__doc__
; followed by variables, function or class defintions.
Standalone Script
The following is a template of standalone scripts:
""" docstring """
# Define variables
......
# Define helper functions
......
# Define main function
def main():
""" main function """
.......
# Run the main function
main()
Class Definition
The syntax is:
class class_name(superclass,...):
class_data = value # class variable
def __init__(self, arg, ...): # constructor
......
def __str__(self, arg, ...): # for printf() and str()
......
def method_name(self, arg, ...):
self.member = arg # instance variable
__author__ = 'Tong Wang'
def main():
'''
Here is the doc!!!
'''
print "Hello World from %s!" % __author__
if __name__ == '__main__':
main()
print main.__doc__