COMP10001 Lecture 5: Week 5
from collections import defaultdict
○
dict = defaultdict(int)
dict[d] += 1
for i in str(x):
return dict
def function(x):
○
defaultdict
-
mylist = []
○
mylist.append(val, key)
for key, val in mydict.items():
[val, key for key, val in mydict.items()]
○
list comprehension turns a for loop into one line
-
Tips and tricks:
a bug = an error/flaw in a piece of code that leads to a malfunction
-
syntax errors = incompatibility with the syntax of the programming language
○
run
-
time errors = errors at run
-
time, causing the code to crash
○
logic errors = design error, such that the code runs but doesn't do what it is supposed to
do
○
bug types
-
debugging = the process of systematically finding and fixing bugs
-
equality vs assignment
○
printing vs returning from functions
○
correct use of types
○
incorrect use of function/method
○
spelling and capitalisation
○
loops and incrementing
○
conditionals and indentation
○
namespace problems
○
things to watch out for
-
Bugs and debugging:
modules = pre
-
pared stores of convenient methods/variables which expand the functionality
of Python
-
import = adds the module to the local namespace
-
from x import * = imports all methods and constants from a library into the local namespace
-
from x import a, b = selectively import objects
-
from x import a as b = import a but rename it as b
-
Modules:
to read data from a local file:
-
FILENAME = "qwerty.txt"
text = open(FILENAME).read()
lines = open(FILENAME).readlines()
f = open(FILENAME)
.read() = reads the entire file
-
.readlines() = reads into a list of lines
-
for line in file = iterates over lines in the file
-
to write to a file:
-
FILENAME = "qwerty.txt"
Files:
Week 5
Wednesday, 4 April 2018 6:51 PM
Foundations of Computing Page 1