python lectures 3

28
Python Crash Course Python Crash Course Programming Programming Bachelors V1.0 dd 13-01-2015 Hour 5

Upload: palimarium

Post on 15-Apr-2016

23 views

Category:

Documents


3 download

DESCRIPTION

python presentation

TRANSCRIPT

Page 1: Python Lectures 3

Python Crash CoursePython Crash CourseProgrammingProgramming

BachelorsV1.0

dd 13-01-2015Hour 5

Page 2: Python Lectures 3

Good programming practiceGood programming practice

• Compromise between:– producing results quickly

and – easy reusability and adaptation of code– code that can be quickly understood by others

• Comment clearly• Use functions• Use modules• Consider ‘refactoring’ before code gets too messy

• Science, not software development

Page 3: Python Lectures 3

Good programming practiceGood programming practice

• The whole works– Execution -- def, class, etc are executable statements that add

something to the current name-space. Modules can be both executable and import-able.

– Statements, data structures, functions, classes, modules, packages.– Functions– Classes– Modules correspond to files with a "*.py" extension. Packages

correspond to a directory (or folder) in the file system; a package contains a file named "__init__.py". Both modules and packages can be imported (see section import statement).

– Packages -- A directory containing a file named "__init__.py". Can provide additional initialization when the package or a module in it is loaded (imported).

Page 4: Python Lectures 3

Good programming practiceGood programming practice

• Blocks and indentationPython represents block structure and nested block structure with indentation, not with begin and end brackets.The empty block -- Use the pass no-op statement.Benefits of the use of indentation to indicate structure:–Reduces the need for a coding standard. Only need to specify that indentation is 4 spaces and no hard tabs.–Reduces inconsistency. Code from different sources follow the same indentation style. It has to.–Reduces work. Only need to get the indentation correct, not both indentation and brackets.–Reduces clutter. Eliminates all the curly brackets.–If it looks correct, it is correct. Indentation cannot fool the reader.

Page 5: Python Lectures 3

Indentation rulesIndentation rules

• Top level must not be indented• It does not matter how many blanks you use, but:

– Uniform within each block– Better avoid tabs

• Most people use 4 blanks per level• If you use emacs python mode, defaults are OK• If you use Windows IDE, defaults are OK too

Page 6: Python Lectures 3

DocstringsDocstrings

• 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: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y | | __coerce__(...) | x.__coerce__(y) <==> coerce(x, y) | | __div__(...) | x.__div__(y) <==> x/y |

Page 7: Python Lectures 3

Introduction to language - conditionalsIntroduction to language - conditionals

• Indentation is important!– be consistent– use four spaces– do not use tabs

>>> a = 4; b = 3 >>> if a > b: ... result = ‘bigger’ ... c = a - b ... >>> print(result, c) (’bigger’, 1)

>>> a = 1; b = 3 >>> if a > b: ... result = ‘bigger’ ... elif a == b: ... result = ‘same’ ... else: # i.e. a < b ... result = ‘smaller’ ... >>> print resultsmaller

>>> if a < b: print ‘ok’ ok

Comparison operators:== != > < >= <= is is not in not in

Boolean operators:and or not

Page 8: Python Lectures 3

Membership and Identity OperatorsMembership and Identity Operators

Operator Description Examplein Evaluates to true if it finds a

variable in the specified sequence and false otherwise.

x in y, here in results in a 1 if x is a member of sequence y.

not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

x not in y, here not in results in a 1 if x is a member of sequence y.

There are two membership operators explained below:

Operator Description Exampleis Evaluates to true if the

variables on either side of the operator point to the same object and false otherwise.

x is y, here is results in 1 if id(x) equals id(y).

is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

x is not y, here is not results in 1 if id(x) is not equal to id(y).

There are two Identity operators explained below:

Page 9: Python Lectures 3

Operators PrecedenceOperators Precedence

Operator Description** Exponentiation (raise to the power)

~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+ - Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'^ | Bitwise exclusive `OR' and regular `OR'<= < > >= Comparison operators

<> == != Equality operators= %= /= //= -= += *= **= Assignment operatorsis is not Identity operatorsin not in Membership operatorsnot or and Logical operators

The following table lists all operators from highest precedence to lowest.

Page 10: Python Lectures 3

Introduction to language - conditionalsIntroduction to language - conditionals

General format:if <test1>:

<statements1>elif <test2>:

<statements2>else:

<statements3>

>>> if 'Steven' in ['Bob', 'Amy', 'Steven', 'Fred']: ... print 'Here!' ... Here!

>>> if 'Carol' not in ['Bob', 'Amy', 'Steven', 'Fred']: ... print 'Away!' ... Away!

>>> test = a == b >>> if test: print 'Equal' 'Equal'

>>> x = int(raw_input("Please enter an integer: ")) >>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1: ... print 'Single'... elif x == 2:... Print 'Double'... else:... print 'More'

Page 11: Python Lectures 3

Introduction to language - truthIntroduction to language - truth

Other datatypes can also express truth:>>> x = 42>>> if x:... print "true"... else:... print "false"

Comparisons yield Boolean values>>> t = 1==1 # Boolean: True>>> f = 0==1 # Boolean: False>>> # Boolean operators:>>> t and False>>> True or f>>> not True>>> # Precedence: ( > not > and > or:>>> False or True and not False>>> (not False or True) == (not (False or True))

Boolean expression can combine different datatypes:>>> 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

Equality and Identity>>> l = [1,2,3]>>> m = l>>> # Equality (of values) tested with ==>>> l == m>>> # Identity (of objects) tested with is>>> l is m # l and m same object!>>> id(l)>>> id(m)>>> l[0] = 42>>> print l>>> print m # m[0] = ?

Page 12: Python Lectures 3

Introduction to language - loopsIntroduction to language - loops

General format:while <test1>: # loop test <statements1> # loop bodyelse: # optional else <statements2> # run if loop didn't break # run if while becomes false

>>> a = b = 0 >>> while a < 10: ... a += 3 ... print(a) ... 3 6 9 12 >>> while True: ... b += 3 ... if b >= 10: break ... print(b) 3 6 9 >>> a = 0>>> while a < 5: a +=1>>> print a5

Page 13: Python Lectures 3

Introduction to language - loopsIntroduction to language - loops

for <target> in <object>: <statements>else: # optional, didn't hit a break <other statements>

>>> for i in [2, 5, 3]: ... print(i**2) 4 25 9

>>> for j in range(5): print(j) 0 1 2 3 4

>>> range(3, 10, 2) [3,5,7,9]

>>> d = {'this': 2, 'that': 7} >>> for k, v in d.items(): ... print('%s is %i'%(k, v)) this is 2 that is 7

• For is a sequence iterator– Steps through items in a list, string, tuple, class, etc– Can use break, continue, pass as in while– Can be used with range to make counter loops

Page 14: Python Lectures 3

Introduction to language - Loop controlIntroduction to language - Loop control

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

#!/usr/bin/python

for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter

Current Letter : P Current Letter : y Current Letter : t

#!/usr/bin/python

for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter

Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n

Page 15: Python Lectures 3

Introduction to language - Loop controlIntroduction to language - Loop controlThe pass statement is used when a statement is required syntactically but you do not want any command or code to execute.The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet

#!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!"

Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye!

An else statement associated with a loop statements.•If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.•If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

#!/usr/bin/python for num in range(10,17): for i in range(2,num): if num%i == 0: j=num/i print '%d equals %d * %d' % (num,i,j) break else: print num, 'is a prime number‘

10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number

Page 16: Python Lectures 3

Documentation and testsDocumentation and tests

• Comments before function, class, etc. are used to generate help• “Docstrings”

– preferred way of documenting code– can contain examples, which are automatically turned into tests!

• See doctest module

>>> # My totally wicked function >>> def my_func(x, y=0.0, z=1.0): ... ”””This does some stuff. ... For example: >>> my_func(1.0, 3.0, 2.0) 8.0 Yep, it’s that good! ””” ... a = x + y ... b = a * z ... return b

Page 17: Python Lectures 3

Good programmingGood programming

• Code layout– 4 spaces indentation– continue sensibly

# Aligned with opening delimiterfoo = long_function_name(var_one, var_two, var_three, var_four)

# More indentation included to distinguish this from the rest.def long_function_name( var_one, var_two, var_three, var_four): print(var_one)

my_list = [ 1, 2, 3, 4, 5, 6,]result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f',)

Page 18: Python Lectures 3

Good programmingGood programming

• Long lines

with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())

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)

Page 19: Python Lectures 3

Good programmingGood programming

• Long strings

>>> print 'o' 'n' "e"one

The spaces between literals are not required, but help with readability. Any type of quoting can be used:>>> print 't' r'\/\/' """o"""t\/\/o

long_string = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' 'sed do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Ut enim ad minim veniam, quis nostrud exercitation ' 'ullamco laboris nisi ut aliquip ex ea commodo consequat. ' 'Duis aute irure dolor in reprehenderit in voluptate velit ' 'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' 'occaecat cupidatat non proident, sunt in culpa qui officia ' 'deserunt mollit anim id est laborum.')

"""Tripledoublequotes""“

'''\Triplesinglequotes\''‘

Page 20: Python Lectures 3

Good programmingGood programming

• White spaceYes: spam(ham[1], {eggs: 2})No: spam( ham[ 1 ], { eggs: 2 } )

Yes: if x == 4: print x, y; x, y = y, xNo: if x == 4 : print x , y ; x , y = y , x

Yes:i = i + 1submitted += 1x = x*2 - 1hypot2 = x*x + y*yc = (a+b) * (a-b)

No:i=i+1submitted +=1x = x * 2 - 1hypot2 = x * x + y * yc = (a + b) * (a - b)

Page 21: Python Lectures 3

Introduction to language - helpIntroduction to language - help

• Powerful help tools• Every object, function, module, .., can be inspected

>>> help(math)

>>> help(math.cos)

>>> a = [1, 2, 3] >>> help(a)

>>> print a.__doc__

Page 22: Python Lectures 3

Introduction to language - exceptionsIntroduction to language - exceptions

Languages that don’t have exception handling built in (e.g. FORTRAN,C) tend to have code that is sprinkled with code like this:

ratio = 0.0;if (x == 0) { printf("Divisor = 0");} else { ratio = y/x;}

In Python (and C++, Java and other more modern languages), an errorwill throw an exception, which you can then handle. So the equivalentcode in Python would look like...

Page 23: Python Lectures 3

Introduction to language - exceptionsIntroduction to language - exceptions

Try-except

x = 0.0try: ratio = y/xexcept ZeroDivisionError: print 'Divisor = 0'

The try/except syntax has the advantage that what you want to doappears first, you don’t have to read past a lot of error trapping code tofind 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

Page 24: Python Lectures 3

Introduction to language - exceptionsIntroduction to language - exceptions

Try-exceptimport systry: untrusted.execute()except: # catch *all* exceptions e = sys.exc_info()[0] write_to_page( "<p>Error: %s</p>" % e )

import sys

try: f = open('myfile.txt') s = f.readline() i = int(s.strip())except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror)except ValueError: print "Could not convert data to an integer."except: print "Unexpected error:", sys.exc_info()[0] raise

BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError | | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError | +-- NameError | | +-- UnboundLocalError | +-- ReferenceError

| +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | +-- TypeError | +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning

+-- ImportWarning +-- UnicodeWarning +-- BytesWarning

Page 25: Python Lectures 3

TestingTesting

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.

Page 26: Python Lectures 3

UnittestsUnittests

• makes each code test itself for error free functioning– example from random module code

import unittest

class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10)

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()

Page 27: Python Lectures 3

TestingTesting

• unittest– unittest is the batteries-included test module in the Python standard library.

import unittest

def fun(x): return x + 1

class MyTest(unittest.TestCase): def test(self): self.assertEqual(fun(3), 4)

Page 28: Python Lectures 3

Introduction to languageIntroduction to language

End