If you already know Python, go find another talk.
Many people at Plone Conference don't know Python.
This talk is for Plone Conference people who don't know Python.
This talk will move extremely fast.
About one slide every twelve seconds.
Look at the code.
Listen to the descriptions.
This talk will not teach you Python.
This talk will teach you what you need to know about Python.
Only by study and practice will you learn Python.
This talk will allow you to judge whether learning Python is right for you.
You will likely be dizzy and confused by the end of this talk.
That's OK.
You will know the scope of what you may want to learn by the end of this talk.
And you can follow along at your own pace later.
> python
> python >>>
The Python prompt is waiting for you!
> python >>> 1 + 2 * 3
This is an example of a Python expression.
> python >>> 1 + 2 * 3 7 >>>
Evaluating an expression at the Python prompt results in the interpreter representing the value of the expression.
> python >>> 1 + 2 * 3 7 >>> print "OK"
This is an example of a Python print statement.
> python >>> 1 + 2 * 3 7 >>> print "OK" OK >>>
Executing a Python statement involves one of more Python keywords.
>>> help("keywords")
Evaluate the built-in help() function with the argument "keywords" to see a list of all keywords known to your Python interpreter.
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
and else import raise
assert except in return
break exec is try
class finally lambda while
continue for not yield
def from or
del global pass
elif if print
>>>
Python is a simple language with very few keywords compared to other languages.
>>> ^D >
Type your system's end of file character to end your session at the Python prompt.
Contents of myscript.py:
print "OK"
> python myscript.py OK >
> python path/to/myscript.py OK >
Use a relative path if myscript.py is in a subdirectory of the current directory.
> python /path/to/myscript.py OK >
You may always use an absolute path to your script.
Contents of myscript.py:
#! /usr/bin/python print "OK"
The "she-bang" line tells a non-Windows OS to interpret the file with a specific Python interpreter.
Contents of myscript.py:
#! /usr/bin/env python print "OK"
non-Windows:
> chmod +x myscript.py > ./myscript.py OK >
The script must be executable to use the she-bang line.
Windows:
> ftype Python.Script="C:\Python24\python.exe" "%1" "%*" > assoc .py=Python.Script > myscript.py OK >
Windows:
> ftype Python.Script="C:\Python24\python.exe" "%1" "%*" > assoc .py=Python.Script > myscript.py OK >
Windows:
> set PATHEXT=%PATHEXT%;.py > myscript OK >
Set the PATHEXT to include .py file extensions in the list of extensions with interpreters.
The safest way on any platform:
> /full/path/to/python /full/path/to/myscript.py OK >
> python >>> import myscript OK >>>
> python >>> import myscript OK >>> import myscript >>>
Each subsequent reload of the compiled module skips the interpretation step.
> rm -f myscript.py # del myscript.py on Windows > python myscript.pyc OK > python >>> import myscript OK >>>
> ls -l myscript.pyc -rw-r--r-- 1 cbc trizpug 110 Sep 14 16:00 myscript.pyc > vi myscript.py > ls -l myscript.py -rw-r--r-- 1 cbc trizpug 20 Sep 14 16:01 myscript.py > python >>> import myscript OK Already >>> ^D > ls -l myscript.pyc -rw-r--r-- 1 cbc trizpug 118 Sep 14 16:02 myscript.pyc
Just try it!
In Python, everything is an object.
Whenever you ever come across something in Python which makes you ask:
"What is this?"
Your first correct answer is, "an object."
Whenever you ever come across something in Python which makes you ask:
"What is this?"
Your first correct answer is, "an object."
>>> "OK" 'OK' >>> print "OK" OK >>>
Your old friend, the string object "OK."
>>> "OK".__doc__ 'str(object) -> string\n\nReturn a nice string representation of the object. \nIf the argument is a string, the return value is the same object.' >>>
>>> "OK".__doc__ 'str(object) -> string\n\nReturn a nice string representation of the object. \nIf the argument is a string, the return value is the same object.' >>> print "OK".__doc__ str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. >>>
>>> "OK".lower <built-in method lower of str object at 0x69880> >>>
All string objects also have a method named lower.
>>> "OK".lower <built-in method lower of str object at 0x69880> >>> "OK".lower() 'ok' >>>
Calling the lower method evaluates to another string!
>>> "OK".lower <built-in method lower of str object at 0x69880> >>> "OK".lower() 'ok' >>> print "OK".lower() ok >>>
And we may render the string returned by the lower method into a nicer visual representation with a print statement.
>>> print "OK".lower.__doc__ S.lower() -> string Return a copy of the string S converted to lowercase. >>>
The string "OK" has a lower method, which has a __doc__ attribute, which may be rendered with a print statement.
>>> type("OK")
<type 'str'>
>>> type(type("OK"))
<type 'type'>
>>>
>>> type("OK")
<type 'str'>
>>> type(type("OK"))
<type 'type'>
>>> type(type("OK"))("OK")
<type 'str'>
>>>
>>> type("OK")
<type 'str'>
>>> type("OK")("OK")
'OK'
>>> type("OK")(1)
'1'
>>>
>>> type("OK")
<type 'str'>
>>> type("OK")("OK")
'OK'
>>> type("OK")(1)
'1'
>>>
>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
The built-in dir() function return a list of the names of the attributes of the object passed as its argument.
>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
The list will contain at least all the attributes required for an object of the argument's type.
>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
Duck typing: "If it walks like a duck, and quacks like a duck, then it's a duck."
Whenever you ever come across something in Python which makes you ask:
"What is this?"
Your first correct answer is, "an object."
Your next question should then be:
"What type of object is this?"
>>> 3 3 >>> type(3) <type 'int'> >>> 076 62 >>> 0xAE 174 >>>
>>> type("3")
<type 'str'>
>>> int("3")
3
>>>
The built-in int() type object creates a new integer object from a string or floating point argument.
>>> dir(3) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>>
The attributes of an int object are mostly methods concerned with what happens when an integer is used in an arithmetic operation.
>>> print int(3).__add__.__doc__ x.__add__(y) <==> x+y >>> int(3).__add__(2) 5 >>> 3 + 2 5 >>>
For instance, the __add__() method of int objects is invoked whenever an integer is the first operand for the addition ("+") operator.
>>> 9 / 4 2 >>>
>>> 9 / 4 2 >>> 9 % 4 1 >>>
>>> type(3.) <type 'float'> >>> type(3e10) <type 'float'> >>> 3. 3.0 >>> 3e10 30000000000.0 >>>
>>> 1e-6 9.9999999999999995e-07 >>>
Because storing floating point numbers involves converting decimal literals to binary mantissae of limited precision, the accuracy of floating point operations is not perfect.
>>> 1e-6 9.9999999999999995e-07 >>> 1e-6 == 0.000001 True >>>
However, the accuracy is happily consistent.
>>> float(3)
3.0
>>> float("3e10")
30000000000.0
>>>
The built-in float() type object creates a new float object from a string or integer argument.
>>> 123456789012345678901234567890L 123456789012345678901234567890L >>>
>>> 2 ** 31 2147483648L >>>
>>> 3/3.0 1.0 >>> 3L + 3.0 6.0 >>>
Mixing integers or long objects with float objects in numeric expressions results in float objects.
>>> 3 == 3.0 True >>> 3L == 3.0 True >>>
Comparison between numeric objects of different types produces common sense results.
>>> 1+1J (1+1j) >>> 3.5-2.7j (3.5-2.7j) >>>
>>> 2 * 3 + 4j (6+4j) >>> 2 * (3 + 4j) (6+8j) >>>
Use parentheses to disambiguate the order of operations in expressions involving complex number objects.
>>> (3 + 4j).real 3.0 >>> (3 + 4j).imag 4.0 >>>
Complex objects have real and imag attributes.
>>> True True >>> type(True) <type 'bool'> >>> False False >>> type(False) <type 'bool'> >>>
>>> bool(0)
False
>>> bool(-5)
True
>>> bool(0+1j)
True
>>> bool("")
False
>>> bool("OK")
True
>>> bool("OK".lower)
True
>>>
Any Python object may be evaluated for its truth value using the bool() built-in type object.
| x + y | sum of x and y |
| x - y | difference of x and y |
| x * y | product of x and y |
| x / y | quotient of x and y |
| x // y | (floored) quotient of x and y |
| x % y | remainder of x / y |
| -x | x negated |
| +x | x unchanged |
| x ** y | x to the power y |
| x | y | bitwise or of x and y |
| x ^ y | bitwise exclusive or of x and y |
| x & y | bitwise and of x and y |
| x << n | x shifted left by n bits |
| x >> n | x shifted right by n bits |
| ∼x | the bits of x inverted |
| < | strictly less than |
| <= | less than or equal |
| > | strictly greater than |
| >= | greater than or equal |
| == | equal value (equivalency) |
| != | not equal |
All comparison operations result in a True or False Boolean value.
| Good | Bad |
|---|---|
| cbc | 345 |
| CBC | 3BC |
| _ok3 | cbc! |
| ok_3 | ok-3 |
>>> a = 3 >>> a 3 >>>
>>> b Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'b' is not defined >>>
>>> a = 3 >>> a 3 >>> type(a) <type 'int'> >>>
>>> a = 3.0 >>> type(a) <type 'float'> >>>
>>> a = b = c = 3 >>> a 3 >>> b 3 >>> c 3 >>>
An object may be bound to several identifiers simultaneously in one assignment statement.
| x += y | same as x = x + y |
| x -= y | same as x = x - y |
| x *= y | same as x = x * y |
| x /= y | same as x = x / y |
| x //= y | same as x = x // y |
| x **= y | same as x = x ** y |
| x %= y | same as x = x % y |
| x &= y | same as x = x & y |
| x |= y | same as x = x | y |
| x ^= y | same as x = x ^ y |
| x >>= y | same as x = x >> y |
| x <<= y | same as x = x << y |
The combination of strong and dynamic typing is described as duck typing.
If it walks like a duck, and it quacks like a duck, then it's a duck.
>>> a = 3 >>> b = a >>> c = b >>> c 3 >>>
An object may be bound to many identifiers.
>>> a = 3 >>> b = a >>> c = b >>> c 3 >>> a = 5 >>> b 3 >>>
Rebinding one identifier to another object does not rebind the other identifiers.
>>> "OK Already"[3] 'A' >>>
Elements in a sequence are indexed by the subscription operator ("[]").
>>> len("OK Already")
10
>>>
The built-in len() function evaluates the number of elements in a sequence.
>>> "OK Already"[10] Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: string index out of range >>>
Indexing beyond the end of a sequence raises an IndexError Exception.
>>> "OK Already"[-7] 'A' >>>
Negative indices count back from the last element in the sequence.
>>> "OK Already"[-11] Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: string index out of range >>>
Negative indexing before the beginning of a sequence raises an IndexError Exception.
>>> "OK Already"[-1] 'y' >>>
This makes it easy to find the last element in a sequence.
>>> "OK Already"[1:4] 'K A' >>>
>>> "OK Already"[1:7:2] 'KAr' >>>
Slice objects may have an optional third step value.
>>> "OK Already"[3:20] 'Already' >>>
Slicing beyond the end of a sequence does not raise an IndexError Exception.
>>> "OK Already"[-7:-2] 'Alrea' >>>
Negative indices work fine with slice objects.
>>> "OK Already"[7:2] '' >>>
A slice object subscription which ends before it begins evaluates to an empty sequence.
>>> "OK Already"[3:] 'Already' >>>
Omitting the stop value from a slice object is the same as specifying the end of the sequence.
>>> "OK Already"[:2] 'OK' >>>
Omitting the start value from a slice object is the same as specifying the beginning of the sequence.
Escaped characters start with a backslash:
| \\ | Backslash (\) | \n | ASCII Linefeed |
| \' | Single quote (') | \r | ASCII Carriage Return |
| \" | Double quote (") | \t | ASCII Horizontal Tab |
| \a | ASCII Bell | \v | ASCII Vertical Tab |
| \b | ASCII Backspace | \ooo | Character with octal value ooo |
| \f | ASCII Formfeed | \xhh | Character with hex value hh |
>>> print '\'' ' >>>
Print an escaped single quote.
>>> print '\'' ' >>> print "The time is \"now.\"" The time is "now." >>>
Print a couple of escaped double quotes.
>>> print '\''
'
>>> print "The time is \"now.\""
The time is "now."
>>> print "Now\tis\nbetter\fthan\b\bnever."
Now is
better
thnever.
>>>
Print some carriage control characters.
>>> print '\''
'
>>> print "The time is \"now.\""
The time is "now."
>>> print "Now\tis\nbetter\fthan\b\bnever."
Now is
better
thnever.
>>> print r"Now\tis\nbetter\fthan\b\bnever."
Now\tis\nbetter\fthan\b\bnever.
>>>
Print a raw string with unescaped escaped characters.
Contents of myscript.py:
#!/usr/bin/env python
a = """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
"""
print a
An example of a multiline string.
> python myscript.py
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
>
Contents of myscript.py:
#!/usr/bin/env python
a = """
Beautiful is better than ugly.
Explicit is better\fthan implicit.
Simple is better than complex.
"""
print a
An example of a multiline string with an escaped form feed character.
> python myscript.py
Beautiful is better than ugly.
Explicit is better
than implicit.
Simple is better than complex.
>
Contents of myscript.py:
#!/usr/bin/env python
a = r"""
Beautiful is better than ugly.
Explicit is better\fthan implicit.
Simple is better than complex.
"""
print a
An example of a raw multiline string with an unescaped form feed character.
> python myscript.py
Beautiful is better than ugly.
Explicit is better\fthan implicit.
Simple is better than complex.
>
>>> tuple("OK")
('O', 'K')
>>> 42, 23, "OK"
(42, 23, 'OK')
>>>
>>> a = 42, 23, 'OK' >>> a[1] 23 >>> a[-1] 'OK' >>> a[1:] (23, 'OK') >>> len(a) 3 >>>
>>> a = 42, 23, "OK" >>> x, y, z = a >>> x 42 >>> y 23 >>> z 'OK' >>>
>>> a = 42, 23, "OK" >>> x, y = a Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack >>> w, x, y, z = a Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 3 values to unpack >>>
There must be equal number of elements to unpack on both sides of the assignment.
>>> a = 1 >>> b = 2 >>> b, a = a, b >>> a 2 >>> b 1 >>>
Cool Python trick!
>>> "%s depends a lot on %s." % ('Python', 'tuples')
'Python depends a lot on tuples.'
>>>
| d | Signed integer decimal | f | Floating point decimal format |
| i | Signed integer decimal | F | Floating point decimal format |
| o | Unsigned octal | g | Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise |
| u | Unsigned decimal | G | Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise |
| x | Unsigned hexadecimal (lowercase) | c | Single character (accepts integer or single character string) |
| X | Unsigned hexadecimal (uppercase) | r | String (converts any python object using repr()) |
| e | Floating point exponential format (lowercase) | s | String (converts any python object using str() |
| E | Floating point exponential format (uppercase) | % | No argument is converted, results in a "%" character in the result |
>>> "The cost is %.2f dollars." % (100,) 'The cost is 100.00 dollars.' >>>
Conversion specifiers may have a precision modifier for floating point conversions.
>>> "The cost is %10.2f dollars." % (100,) 'The cost is 100.00 dollars.' >>>
Conversion specifiers may have a minimum field width modifier.
>>> "The cost is %*.*f dollars." % (15, 4, 100,) 'The cost is 100.0000 dollars.' >>>
Both minimum field width and precision may be read from the tuple object.
>>> "The cost is %0*.*f dollars." % (15, 4, 100,) 'The cost is 0000000100.0000 dollars.' >>>
Numeric conversions may be zero padded on the left to the minimum field width with a "0" conversion flag.
>>> "The cost is %-*.*f dollars." % (15, 4, 100,) 'The cost is 100.0000 dollars.' >>>
Conversions may be left justified in the minimum field width width with a "-" conversion flag.
>>> "The cost is %+.2f dollars." % (100,) 'The cost is +100.00 dollars.' >>> "The cost is %+.2f dollars." % (-100,) 'The cost is -100.00 dollars.' >>>
Conversions may force a sign character for numeric conversions of both positive and negative values with a "+" conversion flag.
>>> list((42, 23, "OK")) [42, 23, 'OK'] >>> [42,23,"OK"] [42, 23, 'OK'] >>>
>>> a = [42, 23, 'OK'] >>> a[1] 23 >>> a[-1] 'OK' >>> a[1:] (23, 'OK') >>> len(a) 3 >>>
>>> a = [2.0, 'OK', 3+4j, (42, 23, 'OK'), [1,2,3]] >>> a [2.0, 'OK', (3+4j), (42, 23, 'OK'), [1, 2, 3]] >>> a[1] 'OK' >>> a[1] = 2**31 >>> a [2.0, 2147483648L, (3+4j), (42, 23, 'OK'), [1, 2, 3]] >>>
To replace an element in a list object, put the subscription operator on the left hand side of an assignment statement.
>>> a [2.0, 2147483648L, (3+4j), (42, 23, 'OK'), [1, 2, 3]] >>> del a[2] >>> a [2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3]] >>>
To remove an element from a list object, use the del keyword with the subscription operator.
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3]]
>>> a.append("spam")
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam']
>>>
>>> None >>> type(None) <type 'NoneType'> >>>
>>> None >>> type(None) <type 'NoneType'> >>> dir(None) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] >>> a = None >>> a >>>
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam']
>>> a.extend("OK")
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K']
>>> a.extend((1,2,3))
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3]
>>> a.extend(['python','zope','plone','grok'])
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3,
'python', 'zope', 'plone', 'grok']
>>>
Use the extend() method to add all the elements from another sequence to the end of a list object.
>>> a [2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3, 'python', 'zope', 'plone', 'grok'] >>> del a[5:10] >>> a [2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok'] >>>
slice objects as subsciptions may remove entire slices of a list object using the del keyword.
>>> a [2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok'] >>> a.insert(0,3e6) >>> a [3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok'] >>>
The insert() method of list objects allows you to insert an arbitrary object before any index which already exists.
>>> a [3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok'] >>> a.insert(25,3e6) >>> a [3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok', 3000000.0] >>> a.insert(50,3e6) >>> a [3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok', 3000000.0, 3000000.0] >>>
Or at the end of a list object if the index does not already exist.
>>> a [3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope', 'plone', 'grok', 3000000.0, 3000000.0] >>> a[3:-1] = 'sprint' >>> a [3000000.0, 2.0, 2147483648L, 's', 'p', 'r', 'i', 'n', 't', 3000000.0] >>>
>>> a
[3000000.0, 2.0, 2147483648L, 's', 'p', 'r', 'i', 'n', 't', 3000000.0]
>>> a[3:-1] = ('sprint',)
>>> a
[3000000.0, 2.0, 2147483648L, 'sprint', 3000000.0]
>>>
To replace a slice of a list object with a sequence instead of the elements of a sequence, wrap the replacement sequence in another sequence.
>>> a
[3000000.0, 2.0, 2147483648L, 'sprint', 3000000.0]
>>> a[3:] = ('plone',)
>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>>
To replace a slice of a list object through to the end of the list, omit the stop index of the slice object.
>>> a [3000000.0, 2.0, 2147483648L, 'plone'] >>> b = a[:] >>> b [3000000.0, 2.0, 2147483648L, 'plone'] >>>
You may make a copy of a list object by using a slice object on the right hand side of an assigment statement where both the start and stop indices have been omitted.
>>> a [3000000.0, 2.0, 2147483648L, 'plone'] >>> b = a[:] >>> b [3000000.0, 2.0, 2147483648L, 'plone'] >>> a == b True >>>
The list object and its copy have equivalent value.
>>> a [3000000.0, 2.0, 2147483648L, 'plone'] >>> b = a[:] >>> b [3000000.0, 2.0, 2147483648L, 'plone'] >>> a == b True >>> a is b False >>>
But the original object and its copy are two distinctly different objects.
>>> id(a) 2446960 >>> id(b) 2386320 >>>
The original object and its copy have different object id values.
>>> a [3000000.0, 2.0, 2147483648L, 'plone'] >>> b [3000000.0, 2.0, 2147483648L, 'plone'] >>> a[0] = 'python' >>> b [3000000.0, 2.0, 2147483648L, 'plone'] >>> b[0] = 'zope' >>> a ['python', 2.0, 2147483648L, 'plone'] >>>
The original object and its copy are independent of one another. A change to one does not affect the other.
>>> dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>>
You have already seen the append, extend, and insert methods of list objects.
>>> a = ['bacon','spam','eggs','spam','toast','spam']
>>> a.count('spam')
3
>>>
The count() method returns the number of occurrences of an object in a list object.
>>> a
['bacon', 'spam', 'eggs', 'spam', 'toast', 'spam']
>>> a.index('spam')
1
>>>
The index() method returns the index of the first occurrence of an object in a list object.
>>> a ['bacon', 'spam', 'eggs', 'spam', 'toast', 'spam'] >>> a.pop() 'spam' >>> a ['bacon', 'spam', 'eggs', 'spam', 'toast'] >>> a.pop(2) 'eggs' >>> a ['bacon', 'spam', 'spam', 'toast'] >>>
>>> a
['bacon', 'spam', 'spam', 'toast']
>>> a.remove('spam')
>>> a
['bacon', 'spam', 'toast']
>>> a.remove('spam')
>>> a
['bacon', 'toast']
>>>
>>> a = ['first', 2, 3.0, 4L, 5+0j] >>> a.reverse() >>> a [(5+0j), 4L, 3.0, 2, 'first'] >>>
>>> a = ['one', 42, 'abc', 23, 'two'] >>> a.sort() >>> a [23, 42, 'abc', 'one', 'two'] >>>
>>> dir(()) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__'] >>>
>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
str objects are immutable, too.
>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
But str objects have lots of regular methods!
>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>
Most of which return new str objects.
>>> 'pYtHoN'.capitalize() 'Python' >>>
Return a copy of the str object with only the first character capitalized.
>>> 'python'.center(20) ' python ' >>> 'python'.center(20,'*') '*******python*******' >>>
>>> 'python python python'.count('python')
3
>>> 'python python python'.count('python',6)
2
>>> 'python python python'.count('python',6,15)
1
>>>
>>> 'Python loves strings.'.endswith('strings')
False
>>> 'Python loves strings.'.endswith('strings.')
True
>>>
Return True if the str object ends with the specified suffix str object, False otherwise.
>>> 'Python loves strings.'.endswith(('strings.','tuples.','lists.'))
True
>>> 'Python loves strings.'.endswith('strings.',6)
True
>>> 'Python loves strings.'.endswith('strings.',6,10)
False
>>>
>>> 'Python loves strings.'.startswith('python')
False
>>> 'Python loves strings.'.startswith('Python')
True
>>>
Return True if the str object starts with the specified prefix str object, False otherwise.
>>> 'I\tlove\tPython.'.expandtabs() 'I love Python.' >>> 'I\tlove\tPython.'.expandtabs(6) 'I love Python.' >>>
>>> 'To python, or not to python'.find('python')
3
>>> 'To python, or not to python'.find('python',5)
21
>>> 'To python, or not to python'.find('python',5,21)
-1
>>>
>>> 'To python, or not to python'.index('python')
3
>>> 'To python, or not to python'.index('python',5)
21
>>> 'To python, or not to python'.index('python',5,21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
>>> 'python123'.isalnum() True >>> 'python 123'.isalnum() False >>> ''.isalnum() False >>>
Return True if all characters in the str object are alphanumeric and there is at least one character. False otherwise.
>>> 'python1'.isalpha() False >>> '123'.isdigit() True >>> 'python'.islower() True >>> 'python'.isupper() False >>> '\t\n \f'.isspace() True >>> 'Big Newspaper Headline'.istitle() True >>>
>>> 'python in a nutshell'.title() 'Python In A Nutshell' >>>
>>> ' '.join(['A','day','without','Python','is','like', ... 'a','day','without','sunshine.']) 'A day without Python is like a day without sunshine.' >>>
>>> ''.join(['A','day','without','Python','is','like', ... 'a','day','without','sunshine.']) 'AdaywithoutPythonislikeadaywithoutsunshine.' >>>
>>> print '\n'.join(['A','day','without','Python','is','like', ... 'a','day','without','sunshine.']) A day without Python is like a day without sunshine. >>>
>>> 'python'.ljust(20) 'python ' >>> 'python'.ljust(20,'*') 'python**************' >>>
>>> 'pYtHoN'.lower() 'python' >>> 'pYtHoN'.upper() 'PYTHON' >>>
Return a copy of the str object converted to upper or lower rcase.
>>> ' python '.lstrip()
'python '
>>> '\t\n\tpython\t\n\t'.lstrip()
'python\t\n\t'
>>> 'lalapythonlala'.lstrip('la')
'pythonlala'
>>>
>>> ' python '.strip()
'python'
>>> '\t\n\tpython\t\n\t'.strip()
'python'
>>> 'lalapythonlala'.strip('la')
'python'
>>>
>>> 'python2.4 python2.4 python2.4'.replace('python2.4','python2.5')
'python2.5 python2.5 python2.5'
>>> 'python2.4 python2.4 python2.4'.replace('python2.4','python2.5',2)
'python2.5 python2.5 python2.4'
>>>
>>> 'python\t\npython\t\npython'.split()
['python', 'python', 'python']
>>> 'python**python**python'.split('**')
['python', 'python', 'python']
>>> 'python**python**python'.split('*',1)
['python', '*python**python']
>>>
>>> """ ... Beautiful is better than ugly. ... Explicit is better than implicit. ... Simple is better than complex. ... """.splitlines() ['', 'Beautiful is better than ugly.', 'Explicit is better than implicit.', 'Simple is better than complex.'] >>>
>>> """ ... Beautiful is better than ugly. ... Explicit is better than implicit. ... Simple is better than complex. ... """.splitlines(True) ['\n', 'Beautiful is better than ugly.\n', 'Explicit is better than implicit.\n', 'Simple is better than complex.\n'] >>>
>>> 'pYtHoN'.swapcase() 'PyThOn' >>>
Return a copy of the str object with uppercase characters converted to lowercase and vice versa.
>>> a = '\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0\
... \xef\xee\xed\xec\xeb\xea\xe9\xe8\xe7\xe6\xe5\xe4\xe3\xe2\xe1\xe0\
... \xdf\xde\xdd\xdc\xdb\xda\xd9\xd8\xd7\xd6\xd5\xd4\xd3\xd2\xd1\xd0\
... \xcf\xce\xcd\xcc\xcb\xca\xc9\xc8\xc7\xc6\xc5\xc4\xc3\xc2\xc1\xc0\
... \xbf\xbe\xbd\xbc\xbb\xba\xb9\xb8\xb7\xb6\xb5\xb4\xb3\xb2\xb1\xb0\
... \xaf\xae\xad\xac\xab\xaa\xa9\xa8\xa7\xa6\xa5\xa4\xa3\xa2\xa1\xa0\
... \x9f\x9e\x9d\x9c\x9b\x9a\x99\x98\x97\x96\x95\x94\x93\x92\x91\x90\
... \x8f\x8e\x8d\x8c\x8b\x8a\x89\x88\x87\x86\x85\x84\x83\x82\x81\x80\
... \x7f~}|{zyxwvutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFED\
... CBA@?>=<;:9876543210/.-,+*)(\'&%$#"! \
... \x1f\x1e\x1d\x1c\x1b\x1a\x19\x18\x17\x16\x15\x14\x13\x12\x11\x10\
... \x0f\x0e\r\x0c\x0b\n\t\x08\x07\x06\x05\x04\x03\x02\x01\x00'
>>>
>>> '\x8f\x86\x8b\x97\x90\x91'.translate(a) 'python' >>> '!+*\x8f\x86\x8b+*!\x97\x90\x91*+!'.translate(a,'+!*') 'python' >>>
>>> 'python'.zfill(20) '00000000000000python' >>> 'python python python python'.zfill(20) 'python python python python' >>>
| x in s | True if an element of s is equal to x, else False |
| x not in s | False if an element of s is equal to x, else True |
| s + t | the concatenation of s and t |
| s * n or n * s | n shallow copies of s concatenated |
| s[i] | (floored) i'th element of s, origin 0 |
| s[i:j] | slice of s from i to j |
| s[i:j:k] | slice of s from i to j with step k |
| len(s) | length of s |
| min(s) | smallest element of s |
| max(s) | largest element of s |
>>> 'h' in 'python' True >>> 'yth' in 'python' True >>> 'x' in 'python' False >>>
>>> 'python' in ['python','zope','plone']
True
>>> 'python' in ['perl','ruby','java']
False
>>> 'python' in ('python','zope','plone')
True
>>> 'python' in ('perl','ruby','java')
False
>>>
>>> 'h' not in 'python' False >>> 'yth' not in 'python' False >>> 'x' not in 'python' True >>>
>>> 'python' not in ['python','zope','plone']
False
>>> 'python' not in ['perl','ruby','java']
True
>>> 'python' not in ('python','zope','plone')
False
>>> 'python' not in ('perl','ruby','java')
True
>>>
>>> 'zope' + '/' + 'plone'
'zope/plone'
>>> ['python','zope','plone'] + ['perl','ruby','java']
['python', 'zope', 'plone', 'perl', 'ruby', 'java']
>>> ('python','zope','plone') + ('perl','ruby','java')
('python', 'zope', 'plone', 'perl', 'ruby', 'java')
>>>
>>> 'python' * 3
'pythonpythonpython'
>>> ['python','zope','plone'] * 3
['python', 'zope', 'plone', 'python', 'zope', 'plone',
'python', 'zope', 'plone']
>>> ('python','zope','plone') * 3
('python', 'zope', 'plone', 'python', 'zope', 'plone',
'python', 'zope', 'plone')
>>>
>>> min('python')
'h'
>>> max('python')
'y'
>>> min('PyThOn')
'O'
>>> max('pYtHoN')
't'
>>>
>>> min(['python','zope','plone']) 'plone' >>> max(['python','zope','plone']) 'zope' >>> min(['python','zope','plone',min]) <built-in function min> >>> min(['python','zope','plone',min,3.0]) 3.0 >>> min([3,13,23]) 3 >>> max([3,13,23]) 23 >>>
>>> dict(((1, 'January'), (2, 'February'), (3, 'March')))
{1: 'January', 2: 'February', 3: 'March'}
>>> a = {4:'April', 5:'May', 6:'June'}
>>> a
{4: 'April', 5: 'May', 6: 'June'}
>>>
>>> a[5]
'May'
>>> a[5] = 'Beltane'
>>> a
{4: 'April', 5: 'Beltane', 6: 'June'}
>>>
>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy',
'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys',
'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
Dictionaries have some useful methods.
>>> a
{4: 'April', 5: 'Beltane', 6: 'June'}
>>> a.clear()
>>> a
{}
>>>
>>> a = {1: 'January', 2: 'February', 3: 'March'}
>>> b = a.copy()
>>> b
{1: 'January', 2: 'February', 3: 'March'}
>>> a is b
False
>>> a == b
True
>>>
b is a shallow copy of a.
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>> a.fromkeys(b, 3.0)
{4: 3.0, 5: 3.0, 6: 3.0}
>>> dict.fromkeys(b, 5L)
{4: 5L, 5: 5L, 6: 5L}
>>>
fromkeys() sets all the values in a new dict object from the keys of another dict object.
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a[3]
'March'
>>> a.get(3)
'March'
>>>
get() works almost like the subscription operator.
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a[4]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 4
>>> a.get(4)
>>> a.get(4, 'April')
'April'
>>>
Except that get() avoid raising a KeyError Exception when the key is not found.
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.has_key(3)
True
>>> a.has_key(4)
False
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.items()
[(1, 'January'), (2, 'February'), (3, 'March')]
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.keys()
[1, 2, 3]
>>> a.values()
['January', 'February', 'March']
>>> a.items()
[(1, 'January'), (2, 'February'), (3, 'March')]
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.pop(2)
'February'
>>> a
{1: 'January', 3: 'March'}
>>> a.pop(4)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 4
>>> a.pop(4,'April')
'April'
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.popitem()
(1, 'January')
>>> a
{2: 'February', 3: 'March'}
>>> a.popitem()
(2, 'February')
>>> a.popitem()
(3, 'March')
>>> a.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'popitem(): dictionary is empty'
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>> a.update(b)
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{2: 'Imbolc', 4: 'April'}
>>> a.update(b)
>>> a
{1: 'January', 2: 'Imbolc', 3: 'March', 4: 'April'}
>>>
update() overwrites the values of keys which already exist in the target dict object.
>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.setdefault(3,'April')
'March'
>>> a.setdefault(4,'April')
'April'
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> 3 in a
True
>>> 'March' in a
False
>>> 5 in a
False
>>> 5 not in a
True
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> len(a)
4
>>>
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> del a[3]
>>> a
{1: 'January', 2: 'February', 4: 'April'}
>>>
>>> format = """%(software)s depends a lot on %(datatype)s.
... I like %(software)s."""
>>> dictionary = {'software':'python', 'datatype':'dictionaries'}
>>> print format % dictionary
python depends a lot on dictionaries.
I like python.
>>>
>>> set(((6,), 'five', 4+0j, 3.0, 2L, 1))
set([1, 2L, 3.0, (4+0j), 'five', (6,)])
>>> set('python')
set(['h', 'o', 'n', 'p', 't', 'y'])
>>>
>>> set(([7], (6,), 'five', 4+0j, 3.0, 2L, 1))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>> set('pythonpython')
set(['h', 'o', 'n', 'p', 't', 'y'])
>>>
>>> a = ['eggs','spam','bacon','spam','toast','spam'] >>> a = list(set(a)) >>> a ['toast', 'eggs', 'bacon', 'spam'] >>>
| s.issubset(t) | test whether every element in s is in t |
| s.issuperset(t) | test whether every element in t is in s |
| s.union(t) | new set with elements from both s and t |
| s.intersection(t) | new set with elements common to s and t |
| s.difference(t) | new set with elements in s but not in t |
| s.symmetric_difference(t) | new set with elements in either s or t but not both |
| s.copy() | new set with a shallow copy of s |
| len(s) | cardinality of set s |
| x in s | test x for membership in s |
| x not in s | test x for non-membership in s |
| s <= t | same as s.issubset(t) |
| s >= t | same as s.issuperset(t) |
| s | t | same as s.union(t) |
| s & t | same as s.intersection(t) |
| s - t | same as s.difference(t) |
| s ^ t | same as s.symmetric_difference(t) |
| s.update(t) | update set s, adding elements from t |
| s.intersection_update(t) | update set s, keeping only elements found in both s and t |
| s.difference_update(t) | update set s, removing elements found in t |
| s.symmetric_difference_update(t) | update set s, keeping only elements found in either s or t but not in both |
| s.add(x) | add element x to set s |
| s.remove(x) | remove x from set s; raises KeyError if not present |
| s.discard(x) | removes x from set s if present |
| s.pop() | remove and return an arbitrary element from s; raises KeyError if empty |
| s.clear() | remove all elements from set s |
| s |= t | same as s.update(t) |
| s &= t | same as s.intersection_update(t) |
| s -= t | same as s.difference_update(t) |
| s ^= t | same as s.symmetric_difference_update(t) |
That which is not False is True.
>>> 123 and 456
456
>>> '' and 456
''
>>> 123 and ''
''
>>> 0 and {}
0
>>>
>>> 123 or 456
123
>>> '' or 456
456
>>> 123 or ''
123
>>> 0 or {}
{}
>>>
>>> if raw_input() == '456': ... print "OK" ... else: ... print "Not OK" ... 456 OK >>>
>>> if raw_input() == '456': ... print "OK" ... else: ... print "Not OK" ... 456 OK >>>
>>> if raw_input() == '456': ... print "OK" ... else: ... print "Not OK" ... 789 Not OK >>>
Contents of myscript.py:
a = raw_input("Show me the way: ")
if a == '123':
print 'Up.'
elif a == '456':
print 'Down.'
else:
print 'Sorry!'
> python myscript.py Show me the way: 123 Up. > python myscript.py Show me the way: 456 Down. > python myscript.py Show me the way: 789 Sorry! >
>>> a = 2 >>> while True: ... a = a**1.01 ... print a ...
2.01391110011 2.02805952908 ... 2.31395916722e+303 2.50034103172e+306 Traceback (most recent call last): File "<stdin>", line 3, in ? OverflowError: (34, 'Result too large') >>>
>>> a = 2 >>> while True: ... a = a**1.01 ... if a > 100: break ... print a ...
2.01391110011 2.02805952908 ... 94.1911963444 98.5712845404 >>>
>>> a = 2 >>> while True: ... a = a**1.01 ... if a > 100: break ... if a < 50: continue ... print a ...
The continue keyword causes the containing loop to skip the remaining statements during the current repitition.
50.1548281185 52.1573927713 ... 94.1911963444 98.5712845404 >>>
Contents of myscript.py:
prompt = "Tell me when: "
a = raw_input(prompt)
while a.lower() != "stop":
b = list(a)
b.reverse()
print ''.join(b)
a = raw_input(prompt)
Contents of myscript.py:
> python myscript.py Tell me when: python nohtyp Tell me when: zope epoz Tell me when: Stop >
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(10,20) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> range(10,20,2) [10, 12, 14, 16, 18] >>> range(20,10,-2) [20, 18, 16, 14, 12] >>>
>>> a = iter('zope')
>>> a.next()
'z'
>>> a.next()
'o'
>>> a.next()
'p'
>>> a.next()
'e'
>>> a.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
>>> a = iter(range(300,0,-100)) >>> a.next() 300 >>> a.next() 200 >>> a.next() 100 >>> a.next() Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>>
>>> for x in range(10): ... print x**2, ... 0 1 4 9 16 25 36 49 64 81 >>>
>>> for x in xrange(10): ... print x**2, ... 0 1 4 9 16 25 36 49 64 81 >>>
>>> breakfast = ['eggs','spam','bacon','spam','toast','spam'] >>> for food in breakfast: ... print "%s for breakfast!" % food.capitalize() ... Eggs for breakfast! Spam for breakfast! Bacon for breakfast! Spam for breakfast! Toast for breakfast! Spam for breakfast! >>>
>>> dictionary = {'python':'fun','zope':'useful','plone':'teh awesome'}
>>> dictionary.items()
[('python', 'fun'), ('zope', 'useful'), ('plone', 'teh awesome')]
>>> for software, description in dictionary.items():
... print "%s is %s." % (software.capitalize(), description)
...
Python is fun.
Zope is useful.
Plone is teh awesome.
>>>
Tuples may unpack directly into a target list of multiple loop control identifiers.
>>> dictionary = {'python':'fun','zope':'useful','plone':'teh awesome'}
>>> for software, description in dictionary.iteritems():
... print "%s is %s." % (software.capitalize(), description)
...
Python is fun.
Zope is useful.
Plone is teh awesome.
>>>
>>> [x**2 for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>>
Equivalent to:
>>> a = [] >>> for x in range(10): ... a.append(x**2) ... >>> a [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>>
Except the list comprehension is an expression.
>>> [x**2 for x in range(10) if x%2] [1, 9, 25, 49, 81] >>>
Equivalent to:
>>> a = [] >>> for x in range(10): ... if x%2: ... a.append(x**2) ... >>> a [1, 9, 25, 49, 81] >>>
x**2 is called the mapping expression.
>>> [x**2 for x in range(10) if x%2] [1, 9, 25, 49, 81] >>>
Equivalent to:
>>> a = [] >>> for x in range(10): ... if x%2: ... a.append(x**2) ... >>> a [1, 9, 25, 49, 81] >>>
x%2 is called the filter expression (if present).
>>> [x*y for x in xrange(2,8,2) for y in xrange(3,9,3)] [6, 12, 12, 24, 18, 36] >>>
Equivalent to:
>>> a = [] >>> for x in xrange(2,8,2): ... for y in xrange(3,9,3): ... a.append(x*y) ... >>> a [6, 12, 12, 24, 18, 36] >>>
Iteration may be nested.
>>> [x**y for x in xrange(6) if x%2 for y in xrange(4)] [1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125] >>>
Equivalent to:
>>> a = [] >>> for x in xrange(6): ... if x%2: ... for y in xrange(4): ... a.append(x**y) ... >>> a [1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125] >>>
Iteration and filter expressions may be interspersed.
>>> [x**y for x in xrange(6) if x%2 for y in xrange(4)] [1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125] >>>
Equivalent to:
>>> a = [] >>> for x in xrange(6): ... if x%2: ... for y in xrange(4): ... a.append(x**y) ... >>> a [1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125] >>>
Iteration and filter expressions may be interspersed.
>>> def f(): ... pass ... >>>
>>> def f(x,a,b,c): ... print "Executing f(%s,%s,%s,%s)" % (x,a,b,c) ... return a*x**2 - b*x + c ... >>>
>>> def f(x,a,b,c): ... print "Executing f(%s,%s,%s,%s)" % (x,a,b,c) ... return a*x**2 - b*x + c ... >>> f(4,3,2,1) Executing f(4,3,2,1) 41 >>> f(4.5,3.4,2.3,1.2) Executing f(4.5,3.4,2.3,1.2) 59.699999999999996 >>> f(5+4j,4-3j,3+2j,2-1j) Executing f((5+4j),(4-3j),(3+2j),(2-1j)) (151+110j) >>>
Arguments are bound to the identifiers in the parameter list when the function is called.
>>> def f(x,a,b,c): ... print "Executing f(%s,%s,%s,%s)" % (x,a,b,c) ... return a*x**2 - b*x + c ... >>> p = f(4,3,2,1) Executing f(4,3,2,1) >>> q = f(4.5,3.4,2.3,1.2) Executing f(4.5,3.4,2.3,1.2) >>> r = f(5+4j,4-3j,3+2j,2-1j) Executing f((5+4j),(4-3j),(3+2j),(2-1j)) >>> (p,q,r) (41, 59.699999999999996, (151+110j)) >>>
>>> def f(x,a,b,c): ... print "Executing f(%s,%s,%s,%s)" % (x,a,b,c) ... return a*x**2 - b*x + c ... >>> type(f) <type 'function'> >>> g = f >>> g(1,2,3,4) Executing f(1,2,3,4) 3 >>>
>>> def install(application, platform='Linux', clients=1): ... format = "Installing %s on %s with %s client(s)." ... print format % (application, platform, clients) ... >>>
Parameters may have default values.
>>> def install(application, platform='Linux', clients=1):
... format = "Installing %s on %s with %s client(s)."
... print format % (application, platform, clients)
...
>>> install('Grok','BSD',3)
Installing Grok on BSD with 3 client(s).
>>> install('Zope',platform='OSX',clients=2)
Installing Zope on OSX with 2 client(s).
>>>
Parameters with default values may have arguments supplied by position or name.
>>> def install(application, platform='Linux', clients=1):
... format = "Installing %s on %s with %s client(s)."
... print format % (application, platform, clients)
...
>>> install('Zope',platform='OSX')
Installing Zope on OSX with 1 client(s).
>>> install('Zope',clients=2)
Installing Zope on Linux with 2 client(s).
>>> install('Zope')
Installing Zope on Linux with 1 client(s).
>>>
Supplying an argument for a parameter with a default value is optional.
>>> def install(application, platform='Linux', clients=1):
... format = "Installing %s on %s with %s client(s)."
... print format % (application, platform, clients)
...
>>> install('Plone',clients=4,platform='AIX')
Installing Plone on AIX with 4 client(s).
>>>
>>> def arglist(a,b,c,*args):
... print a, b, c,
... for x in args:
... print x,
...
>>> arglist('python','zope','plone','grok','repoze','bfg')
python zope plone grok repoze bfg
>>>
>>> def kwlist(a,b,c,*args,**kwargs):
... print a, b, c,
... for x in args: print x,
... for k, v in kwargs.items(): print "%s=%s" % (k,v),
...
>>> kwlist('python','zope','plone',
... 'grok','repoze','bfg',
... hanno=2305,limi=737,runyaga=730)
python zope plone grok repoze bfg hanno=2305 limi=737 runyaga=730
>>>
>>>