UTOSC 2008/90 percent of the Python you need to know (in 90 minutes)
Matt Harrison http://panela.blog-city.com
The Zen of Python:
import this
show memebers (attributes, functions) of instances:
dir()
show docs for modules/classes/functions
help()
help("".zfill)
Variables can point to anything:
my_var = "a string" my_var = 42 # an int
Number very similar to other languages. No int overflow
Interpreter
>>> 2.97 * 94.2 279.774
Print variable
nums=5 nums
Strings:
hello = 'hello' hello = "hello" hello = """this is a paragraph and she said "hi" and it was good"""
String formattting:
var = "is %s " % "matt" var = "is %d " % 20
Functions of string?
dir("")
Lists (mutable) and "tuples" (non-mutable)
alpha = ["a", "b"]
alpha.append("c")
alpha = ("a", "b")
Functions of a list?
dir([])
Slicing:
alpha = ["a", "b", "c"] print alpha[0:1] # 0 to 1 print alpha[0:3:2] # 0 to 3, every other one print alpha[1::2] # ever other one
Range:
range(5) # generate numbers 0 to 4 range(start, end, count) range(99, 1, -1)
Dictionaries (hash maps, or associated arrays)
person = {"name": "bob", "age": 29}
age = person["age"]
Functions of dictionary:
dir({})
Functions:
def my_func(param_1, param_2): """ doc string """ return param_1 + param_2
Functions can have default values:
def add(num, add=5):
Return true if gymnast older than 16:
def is_16(year): return (2009 - year) >= 16
Conditionals:
if x > 90: grade = "A" elif x > 80: grade = "B" else: grade = "C"
While (no switch - use dictionary):
cap = {"utah": "salt lake", "arizona": "phoenix"}
if state in capitals:
print "cap of %s is %s" % (state, cap[state])
else:
print "not there"
Loops:
for item in range(10): print item
Break out of loop with break and continue
Indexes, use enumerate;
anim = ["a", "b", "c"] for index, value in enumerate(animals): print value, index
Return a list of numbers squared:
def squared(numbers):
results = []
for num in numbers:
results.append(num * num)
return results
Open file:
fin = open("food.txt")
for line in fin:
# do stuff
fin.close();
Write to file:
fout = open("bar.txt", "w")
fout.write("hi")
fout.close()
Comma at end of print statement won't add new line
print "hi",
Print integers to file:
fin.open("out.txt", "w")
for i in range(100):
fin.write(str(i)) # cast to string
fin.close()
Class:
class Hello(object):
"doc string"
# or
"""
docs as paragraph
"""
def __init__(self, name):
self.name = name
def talk(self):
print "stuff"
@staticmethod
def main():
print "Hello World"
Hello.main()
h = Hello("thing")
h.talk()
Subclass:
class hi(Hello):
def talk(self):
print "something else"
Try catch:
try: ... except KeyError, e: ... except Exception, e: ...
Raise execption:
raise Exception("my error")