Since Python is currently a popular teaching language, and this is a fourth year course, I expect most students to be familiar with many of the concepts discussed here. Please review this page as needed for coursework, and catch up on any concepts that do not look familiar.
python3 filename.py
python3or interactive mode with file loaded first:
python3 -i filename.py
print(expr)
x=3 y='hi' print(x+y) TypeError: unsupported operand type(s) for +: 'int' and 'str' type(y) class 'str' y=5 % type of y changes here. type(y) class 'int' print(x+y) 8
True
and False
. Notice the uppercase!
type(True) class 'bool' type(true) NameError: name 'true' is not defined
# A comment.
a=3 a==3 True b==3 NameError: name 'b' is not defined
assert j == len(L) - 1.
def
defines a function with name and argument(s).
def f(n): ...implementation of f...Python passes function arguments by "object-reference". If this makes no sense to you, read stupidpythonideas or effbot.org or Rob Heaton. Slightly tricky question (from the first linked page): what does this code print?
def spam(eggs): eggs.append(1) eggs = [2, 3] ham = [0] spam(ham) print(ham)
29//2 = 14
, while 29/2 = 14.5
.
range(100)generates all numbers 0, 1, ..., 99, and
range(10,20)generates 10, 11, ..., 19
Lists are one popular type of sequence.
L = [10,2,3,2,1]
print(L[0]) 10
len(L)
computes length of list L. The indices of list elements range from 0 to len(L) - 1
. Trying to access L[len(L)]
is an error.
L = [3,'a',5]
squares = [x**2 for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
E = [[0 for j in range(n)] for i in range(m)]sets all
E[i][j] = 0
from collections import deque q = deque() q.append('A') element = q.popleft()
westernCanadaAdjList = { 'BC': ['AB'], 'AB': ['BC', 'SK'], 'SK': ['AB', 'MB'], 'MB': ['SK'] }
return a, b, c
returns a tuple (a, b, c)
.
To measure how much time some piece of code has used,
time.process_time()
is a simple way which is available in Python 3.3 and up.
See the
Python Documentation of the time module
and an example of the use in the Tic Tac Toe solver code.
A different, more complex but also more convenient approach is to use the signal module. Example: initialize with
signal.signal(signal.SIGALRM, handler)
Then use it to throw an exception at timeout within a try - except block:
signal.alarm(timelimit)
See the documentation for details on signal, and which parts of that library are supported in which python versions. As always, if it is part of coursework, then make sure it works on the undergrad machines before using it.
def __init__(self, ...optional arguments here...): ... initialization code here...
class GoBoard: def __init__(self, size): self.size = size self.moveNumber = 0 bd = GoBoard(19) print(bd.size, bd.moveNumber)
class GoBoard: # size: the size of the board. An integer in range 2 %lt;= size %lt;= 19. # moveNumber: the number of moves (including pass moves) which # have been played
a, b = b, a+b
for _ in range(5)