Python Crash Course Programming
Python Crash Course Programming
Programming
Bachelors
V1.0
dd 13-01-2015
Hour 5
Comment clearly
Use functions
Use modules
Consider refactoring before code gets too messy
Indentation rules
Docstrings
Doc strings are like comments, but they are carried with executing code.
Doc strings can be viewed with several tools, e.g. help(), obj.__doc__, and,
in IPython, a question mark (?) after a name will produce help.
A doc string is written as a quoted string that is at the top of a module or the
first lines after the header line of a function or class.
We can use triple-quoting to create doc strings that span multiple lines.
>>> a=1.0
>>> help(a)
Help on float object:
class float(object)
| float(x) -> floating point number
|
| Convert a string or number to a floating point number, if possible.
|
| Methods defined here:
Indentation is important!
be consistent
use four spaces
do not use tabs
Comparison operators:
== !=
>
<
>= <=
is is not
in not in
Boolean operators:
and
or
not
Description
Example
in
not in
Example
is
is not
Operators Precedence
The following table lists all operators from highest precedence to lowest.
Operator
Description
**
~ + -
* / % //
+ -
>> <<
&
Bitwise 'AND'
^ |
Comparison operators
<> == !=
Equality operators
Identity operators
in not in
Membership operators
not or and
Logical operators
0 or "not empty"
False or "" or [1,2,3] or 42
42 and [1,2,3]
[1,2,3] and 42
# Boolean expressions are evaluated
# from left to right and return the value
# that determines result
# (Short-circuit evaluation
l = [1,2,3]
m = l
# Equality (of
l == m
# Identity (of
l is m # l and
id(l)
id(m)
l[0] = 42
print l
print m # m[0]
= ?
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> x = 42
>>> if x:
...
print "true"
... else:
...
print "false"
#
#
#
#
#
loop test
loop body
optional else
run if loop didn't break
run if while becomes false
>>>
>>>
...
...
...
3
6
9
12
>>>
...
...
...
3
6
9
>>>
>>>
>>>
5
a = b = 0
while a < 10:
a += 3
print(a)
while True:
b += 3
if b >= 10: break
print(b)
a = 0
while a < 5: a +=1
print a
print(j)
Steps through items in a list, string, tuple, class, etc >>> d = {'this': 2, 'that': 7}
>>> for k, v in d.items():
Can use break, continue, pass as in while
...
print('%s is %i'%(k, v))
Can be used with range to make counter loops
this is 2
that is 7
#!/usr/bin/python
#!/usr/bin/python
Current Letter : P
Current Letter : y
Current Letter : t
Current
Current
Current
Current
Current
Letter
Letter
Letter
Letter
Letter
:
:
:
:
:
P
y
t
o
n
equals 2 *
is a prime
equals 2 *
is a prime
equals 2 *
equals 3 *
equals 2 *
is a prime
5
number
6
number
7
5
8
number
...
a = x + y
...
b = a * z
...
return b
Good programming
Code layout
4 spaces indentation
continue sensibly
Good programming
Long lines
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
Good programming
Long strings
Good programming
White space
>>> help(math)
>>> help(math.cos)
>>> a = [1, 2, 3]
>>> help(a)
>>> print a.__doc__
In Python (and C++, Java and other more modern languages), an error
will throw an exception, which you can then handle. So the equivalent
code in Python would look like...
The try/except syntax has the advantage that what you want to do
appears rst, you dont have to read past a lot of error trapping code to
nd out what a particular block of code is doing
try:
[do some processing]
except SomeError:
[respond to this particular error condition]
raise Some(other)Error
# now let something else handle the error
BaseException
|
+-- RuntimeError
+-- SystemExit
|
|
+-- NotImplementedError
+-- KeyboardInterrupt
|
+-- SyntaxError
+-- GeneratorExit
|
|
+-- IndentationError
+-- Exception
|
|
+-- TabError
+-- StopIteration
|
+-- SystemError
+-- StandardError
|
+-- TypeError
Try-except
|
+-- BufferError
|
+-- ValueError
import sys
|
+-- ArithmeticError
|
+-- UnicodeError
try:
|
|
+-- FloatingPointError
|
+-- UnicodeDecodeError
untrusted.execute()
|
|
+-- OverflowError
|
+-- UnicodeEncodeError
except: # catch *all* exceptions
|
|
+-- ZeroDivisionError
|
+-- UnicodeTranslateError
e = sys.exc_info()[0]
|
+-- AssertionError
+-- Warning
write_to_page( "<p>Error: %s</p>" % e )
|
+-- AttributeError
+-- DeprecationWarning
|
+-- EnvironmentError
+-- PendingDeprecationWarning
|
|
+-- IOError
+-- RuntimeWarning
import sys
|
|
+-- OSError
+-- SyntaxWarning
|
|
+-- WindowsError (Windows)
+-- UserWarning
try:
|
|
+-- VMSError (VMS)
+-- FutureWarning
f = open('myfile.txt')
|
+-- EOFError
+-- ImportWarning
s = f.readline()
|
+-- ImportError
+-- UnicodeWarning
i = int(s.strip())
|
+-- LookupError
+-- BytesWarning
except IOError as e:
|
|
+-- IndexError
print "I/O error({0}): {1}".format(e.errno, e.strerror)
|
|
+-- KeyError
except ValueError:
|
+-- MemoryError
print "Could not convert data to an integer."
|
+-- NameError
except:
|
|
+-- UnboundLocalError
print "Unexpected error:", sys.exc_info()[0]
|
+-- ReferenceError
raise
Testing
Some general rules of testing:
A testing unit should focus on one tiny bit of functionality and prove it correct.
Each test unit must be fully independent.
Try hard to make tests that run fast.
Learn your tools and learn how to run a single test or a test case.
Always run the full test suite before a coding session, and run it again after.
The first step when you are debugging your code is to write a new test
pinpointing the bug.
Use long and descriptive names for testing functions.
When something goes wrong or has to be changed, and if your code has a
good set of tests, you or other maintainers will rely largely on the testing suite
to fix the problem or modify a given behavior.
Another use of the testing code is as an introduction to new developers.
import unittest
Unittests
class TestSequenceFunctions(unittest.TestCase):
makes
each code test itself for error free functioning
def setUp(self):
example
self.seq from
= range(10)
random module code
def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)
def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)
if __name__ == '__main__':
unittest.main()
Testing
unittest
import unittest
def fun(x):
return x + 1
class MyTest(unittest.TestCase):
def test(self):
self.assertEqual(fun(3), 4)
Introduction to language
End