| prev | Version 1134 (Mon Nov 27 20:45:58 2006) | next |
![[Human Time vs. Machine Time]](./img/py01/human_vs_machine_time.png)
Figure 7.1: Human Time vs. Machine Time
PythonNumeric package isn't badPython Cookbook for the on-line version![[Sturdy vs. Nimble Execution]](./img/py01/sturdy_vs_nimble.png)
Figure 7.2: Sturdy vs. Nimble Execution
$ pythonPython 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> print 124/284>>> print 124.0/28.04.4285714285714288>>> ^D
"^D" represents control-D, which is Unix's way of saying “end of input”.py extension, and type python filename.py$ cat saved.pyprint 124/28print 124.0/28.0$ python saved.py44.42857142857
#!/usr/bin/python the first line of the program/usr/bin/python with the rest of the file as its inputwhich python to find out#!/usr/bin/env python as the first line/usr/bin/env to find Python, then run the script with it$ cat hashbang.py#!/usr/bin/env pythonprint 124/28print 124.0/28.0$ hashbang.py44.42857142857
.py files with Python.py will then run itplanet = "Pluto" moon = "Charon" p = planet
![[Variables Refer to Values]](./img/py01/vars_values.png)
Figure 7.3: Variables Refer to Values
planet = "Pluto" moon = "Charon" p = planet planet = 9
![[Variables Are Untyped]](./img/py01/vars_untyped.png)
Figure 7.4: Variables Are Untyped
planet = "Sedna" print plant # note the misspelling
Traceback (most recent call last):
File "lec/inc/py01/undefined_var.py", line 2, in ?
print plant # note the misspelling
NameError: name 'plant' is not defined
"#" to the end of the line is a commentx = "two" # "two" is a string y = 2 # 2 is an integer print x * y # multiplying a string concatenates it repeatedly print x + y # but you can't add an integer and a string
twotwoTraceback (most recent call last):File "lec/inc/py01/add_int_str.py", line 4, in ?print x + y # but you can't add an integer and a stringTypeError: cannot concatenate 'str' and 'int' objects
print statement prints zero or more values to standard outputprint on its own just prints a blank lineplanet = "Pluto" num_moons = 1 moon = "Charon" print planet, "has", num_moons, "satellite", print "and its name is", moon
Pluto has 1 satellite and its name is Charon
print "He said, \"It ain't what you know, it's what you can.\""
He said, "It ain't what you know, it's what you can."
print "Sedna was discovered in 2004" print 'It takes 10,500 years to circle the sun.' print '''The tiny world may be part of the Oort Cloud, a shell of icy proto-comets left over from the formation of the Solar System.'''
str converts things to stringsprint "Diameter: " + str(1280) + "-" + str(1760) + " km"
Diameter: 1280-1760 km
int, float, etc. to convert values to other typesprint int(12.3) print float(4)
12 4.0
"\t" and newline "\n"| Expression | Meaning |
|---|---|
\\ | backslash |
\' | single quote |
\" | double quote |
\b | backspace |
\n | newline |
\r | carriage return |
\t | tab |
| Table 7.1: Character Escape Sequences | |
14 is an integer (32 bits long on most machines)14.0 is double-precision floating point (64 bits long)1+4j is a complex number (two 64-bit values)x.real and x.imag to get the real and imaginary parts123456789L is a long integer** for exponentiation| Name | Operator | Use | Value | Notes |
|---|---|---|---|---|
| Addition | + | 35 + 22 | 57 | |
'Py' + 'thon' | 'Python' | |||
| Subtraction | - | 35 - 22 | 13 | |
| Multiplication | * | 3 * 2 | 6 | |
'Py' * 2 | 'PyPy' | 2 * 'Py' is illegal | ||
| Division | / | 3.0 / 2 | 1.5 | |
3 / 2 | 1 | Integer division rounds down: -3 / 2 is -2, not -1 | ||
| Exponentiation | ** | 2 ** 0.5 | 1.4142135623730951 | |
| Remainder | % | 13 % 5 | 3 | |
| Table 7.2: Numeric Operators in Python | ||||
x += 3 does the same thing as x = x + 35 += 3 is an error, since you can't assign a new value to 5…True and False are true and false (d'oh)and, or, not| Expression | Result | Notes |
|---|---|---|
True or False | True | |
True and False | False | |
'a' or 'b' | 'a' | or is true if either side is true, so it stops after evaluating 'a' |
'a' and 'b' | 'b' | and is only true if both sides are true, so it doesn't stop until it has evaluated 'b' |
0 or 'b' | 'b' | 0 is false, but 'b' is true |
0 and 'b' | 0 | Since 0 is false, Python can stop evaluating there |
0 and (1/0) | 0 | 1/0 would be an error, but Python never gets that far |
(x and 'set') or 'not set' | It depends | If x is true, this expression's value is 'set'; if x is false, it is 'not set' |
| Table 7.3: Boolean Operators in Python | ||
and and or are short-circuit operatorsTrue or False)![[Short-Circuit Evaluation]](./img/py01/short_circuit_eval.png)
Figure 7.5: Short-Circuit Evaluation
val = cond and left or rightcond is True, val is assigned leftcond is False, val is assigned right| Expression | Value |
|---|---|
3 < 5 | True |
3.0 < 5 | True |
3 != 5 | True |
3 == 5 | False |
3 < 5 <= 7 | True |
3 < 5 >= 2 | True (but please don't write this—it's hard to read) |
3+2j < 5 | Error: can only use == and != on complex numbers |
| Table 7.4: Comparison Operators in Python | |
= for assignment== to test if two things have equal values| Expression | Value |
|---|---|
'abc' < 'def' | True |
'abc' < 'Abc' | False |
'ab' < 'abc' | True |
'0' < '9' | True |
'100' < '2' | True |
| Table 7.5: String Comparisons in Python | |
if, elif (not else if), and elsea = 3
if a < 0:
print 'less'
elif a == 0:
print 'equal'
else:
print 'greater'
greater
begin/end or {…}?num_moons = 3
while num_moons > 0:
print num_moons
num_moons -= 1
3 2 1
print 'before'
num_moons = -1
while num_moons > 0:
print num_moons
num_moons -=1
print 'after'
before after
num_moons = 3
while num_moons > 0:
print num_moons
# oops --- forgot to subtract one
3 3 3⋮
breaknum_moons = 3
while True: # Looks like an infinite loop...
print num_moons
num_moons -= 1
if num_moons <= 1:
break # ...but there's a way out
3 2
continuenum_moons = 5
while num_moons > 0:
print 'top:', num_moons
num_moons -= 1
if (num_moons % 2) == 0:
continue
print '...bottom:', num_moons
top: 5 top: 4 ...bottom: 3 top: 3 top: 2 ...bottom: 1 top: 1
% operator formats output'here %s go' % 'we' creates "here we go""%s" in the left string means “insert a string here”'left %d right %d' % (-1, 1) creates "left -1 right 1""%d" stands for “decimal integer”'%04d' % 13 creates "0013"'[%-4d]' % 13 creates "[13 ]"'%6.4f %%' % 37.2 creates "37.2000 %""%%" is translated into a single "%""\\" is how you represent a single "\" in a string| Format | Meaning | Example | Output |
|---|---|---|---|
"d" | Signed decimal integer | '%d %d' % (13, 15) | "13 15" |
"o" | Unsigned octal (base-8) | '%o %o' % (13, 15) | "15 17" |
"x" | Lower case unsigned hexadecimal (base-16) | '%x %x' % (13, 15) | "d f" |
"X" | Upper case unsigned hexadecimal (base-16) | '%X %X' % (13, 15) | "D F" |
"e" | Lower case exponential floating point | '%e' % 123.45 | "1.234500e+02" |
"E" | Upper case exponential floating point | '%E' % 123.45 | "1.234500E+02" |
"f" | Decimal floating point | '%f' % 123.45 | "123.4500" |
"s" | String (converts other types using str()) | '%s %s %s' % ('nickel', 28, 58.69) | "nickel 28 58.69" |
| Table 7.6: String Formats in Python | |||
| prev | Copyright © 2005-06 Python Software Foundation. | next |