Fundamental tradeoff between:
How quickly correct code can be written
How quickly that code executes
People are expensive
Makes sense to write:
Time-critical libraries at a low level for speed
Everything else at the highest possible level
Pro:
Like the Unix shell, only better
(Much) more readable than Perl
Object-oriented
But not religious about it
Easy to integrate with C, Fortran, Java
Con:
Slower than C
But often as fast as Java
Things that make small programs easy to write can make large ones hard to maintain
# Run with "python helloworld.py" # Assign a string to a variable. # Note: no 'main()', no declarations str = "Hello" # Print strings (plus newline). print str, "world!" prints "Hello world!\n" # Print strings (plus space). print str, "world!", prints "Hello world! " # Print strings (without newline or space). import sys; sys.stdout.write(str + " world!") sys.stdout.flush(); prints "Hello world!"
Interactively (good for debugging)
By putting code in file, and loading it
$ python myfile.py
By making a native executable
Unix: #!/usr/bin/env python
Windows: File association
By compiling to a self-contained program
Instructions are still actually interpreted
$ python >>> 3+5 8 >>> x = 3 * 7 ** 2 >>> print x 147 >>> x = "some" + "thing" >>> print x something
Variables are just names for values
Created by use
No declarations
Variables don't have types, but values do
x = 123 # integer y = "one two three" # string z = x + y TypeError: unsupported operand types for +
Must give a variable a value before using it
Python doesn't try to guess a sensible value
# This is the whole program print y NameError: name 'y' is not defined
See how to handle errors later
Use either single or double quotes
Must be consistent
Newlines must be escaped with backslashes
print 'Always', "plan", '"ahea\ d"' Always plan "ahead" print "ahea d" SyntaxError: invalid token
Use triple quotes to represent long strings
Newlines need not be escaped
print """Poetic em phas is""" Poetic em phas is
Back-quoting converts value to string
print "carbon-" + 14 TypeError: cannot concatenate 'str' and 'int' objects print "carbon-" + `14` carbon-14
Typecast converts value to integer
print "1" + 1
TypeError: cannot concatenate 'str' and 'int' objects
print int("1") + 1
2
The usual numeric types
14 is an integer (32-bit on most machines)
14.0 is floating point (64-bit)
1+4j is complex (2 x 64-bit)
Python borrows C's numeric operators
Including in-place forms
x = 5 * 4 + 3 # x now 23 x -= 10 # x now 13 y = x % 3 # remainder is 1
Values:
True and False are true and false (d'oh)
Empty string, 0, and None are false
(Almost) everything else is true
Usual Boolean operators (and, or, not)
Short-circuit
Return the last thing evaluated, rather than 1 or 0
What is the result of each of the following statements?
print "a" or "b" a print 0 or "a" a print "a" and "b" b print "a" and 0 and 1 and (1/0) 0 print "a" and "0" and 1 and (1/0) ZeroDivisionError: integer division or modulo by zero
Python borrows C's comparisons
Results are always 1 (true) or 0 (false)
= is assignment, == is equality
Assignment is a statement, not an expression
Strings are compared in dictionary order
print 3 < 5, 2.1 >= 2.2, "a" < "A", "Abc" < "AB" 1 0 0 0
Comparisons can be chained together, as in mathematics
print -1 < 0 < 1 1
Use + for concatention, * for multiplication
greet = "Hi " + "there" Hi there jolly = "ho" * 3 hohoho
if, elif, and else
Use colon and indentation to show nesting
a = 3
if a < 0:
print "less"
elif a == 0:
print "equal"
else:
print "greater"
greater
Based on studies from 1980s
It's what everyone looks at anyway
Just count the number of warnings in C/Java books about misleading indentation
Use colon and indentation to show nesting
a = 3
while a > 0:
print a
a -= 1
3
2
1
Use built-in function file() to open a file
First argument is path
Second is "r" (for read) or "w" for write
Result is a file object with methods for input and output
# Copy one file to another
input = file("file.txt", "r") # open file.txt for reading
output = file("copy.txt", "w") # open copy.txt for writing
line = input.readline() # get first line
while line: # 'None' indicates end-of-file
output.write(line) # copy line to output
line = input.readline() # try for another line
input.close() # don't need file any longer
output.close() # we're done
Could also write this as:
input = file("file.txt", "r")
output = file("copy.txt", "w")
for line in input:
output.write(line)
input.close()
output.close()
Or:
input = file("file.txt", "r")
contents = input.readlines()
input.close()
output = file("copy.txt", "w")
output.writelines(contents)
output.close()