To get to the python interpreter, where you can type freely, just run
python
Within the interpreter, you can get help:
dir(5)
You can get an interactive help system:
help()
Basics ∞
# Comment """This is a multiline comment. The following lines concatenate the two strings.""" '''this is also multiline''' print "test" print "append this to get help about an object".__doc__ # Variables a="a variable" print "you can do this", a # List print "testing %s here" % [a, 2, 3] # Dictionary print "This %(verb)s a %(noun)s." % {"noun": a, "verb": "is"} # Tuple print "a string can have %s in it" % (a)
a=b=2 print a # 2 print b # 2
Strings ∞
https://docs.python.org/3/library/string.html
import string a="A test" print string.lower(a) # There is no case-insensitive replace. =/ print string.replace(a, "A ", "") a="one string" b="another string" print a + " " + b print string.join(a, "_") a='Hello, wOrLD' print a.title()
Data structures ∞
http://docs.python.org/tutorial/datastructures.html
Lists [] ∞
http://docs.python.org/c-api/list.html
Lists are like one-dimensional arrays (but you can also have lists of other lists)
mylist = ["List item 1", 2, 3.14] # Python counts from 0. Sigh. mylist[0] = "List item 1 again"
List comprehension ∞
http://docs.python.org/tutorial/datastructures.html#list-comprehensions
a=[1,2,3] b=[]
The "hard", but obvious, way:
for x in a: for y in a: b.append(x * y) print b
The "easy", but inobvious, way:
print [x * y for x in a for y in a]
Dictionaries {} ∞
http://docs.python.org/c-api/dict.html
Dictionaries are associative arrays (a.k.a. hash tables)
mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14} mydict["pi"] = 3.15
Tuples () ∞
http://docs.python.org/c-api/tuple.html
Tuples are immutable one-dimensional arrays. Python "arrays" can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples.
mytuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # You can do standard stuff.. print mytuple[0] print mytuple[8:] print mytuple[:2] print mytuple[2:4]
TODO: Sets ∞
http://docs.python.org/library/sets.html
# TODO: I don't understand this example.. from sets import Set engineers = Set(['John', 'Jane', 'Jack', 'Janice']) programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) employees = engineers | programmers | managers # union engineering_management = engineers & managers # intersection fulltime_management = managers - engineers - programmers # difference engineers.add('Marvin') # add element print engineers # doctest: +SKIP Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) employees.issuperset(engineers) # superset test employees.update(engineers) # update from another set employees.issuperset(engineers) for group in [engineers, programmers, managers, employees]: # doctest: +SKIP group.discard('Susan') # unconditionally remove element print group Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) Set(['Janice', 'Jack', 'Sam']) Set(['Jane', 'Zack', 'Jack']) Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
Flow Control ∞
http://docs.python.org/tutorial/controlflow.html
# There is also 'break' (stop), 'continue' (skip), 'pass' (skip) for i in [1, 2, 3, 4]: if i in [2, 3]: print "%s is 2-3" % (i) else: print "%s is not 2-3" % (i) for i in [1, 2, 3, 4]: if i == 3: print "I found three" elif i == 2: print "I found two" else: print "I found something else: ", i i=0 while i != 4: print i i += 1
Functions ∞
https://docs.python.org/3/library/functions.html [ 1 ] was http://docs.python.org/library/functions.html
functionvar = lambda x: x + 1 print functionvar(1) # 2 print functionvar(2) # 3 def function(): print "this function works" function # This won't do anything function() def function(a, b): print "I got a: ", a print "I got b: ", b function("one", "two")
TODO: Classes ∞
http://docs.python.org/tutorial/classes.html
Errors and Exceptions ∞
http://docs.python.org/tutorial/errors.html
def error_test(): try: # Division by zero raises an exception 10 / 0 except ZeroDivisionError: print "Oops, invalid." else: # Exception didn't occur, we're good. pass finally: # This is executed after the code block is run # and all exceptions have been handled, even # if a new exception is raised while handling. print "We're done with that." error_test()
Modules ∞
https://docs.python.org/3/tutorial/modules.html [ 2 ] was http://docs.python.org/tutorial/modules.html
For importing another script, or something that came with Python.
import random from time import clock
FIXME/TODO: stuff ∞
http://docs.python.org/tutorial/modules.html#executing-modules-as-scripts
If script.py
has something like this:
def function(a) print "I got: ", a if __name__ == "__main__": import sys function(int(sys.argv[1]))
You can do
python script.py <arguments>
TODO - Input/Output (I/O) ∞
http://docs.python.org/tutorial/inputoutput.html
Footnotes
Last updated 2021-05-29 at 22:51:29
ported