Download presentation
Presentation is loading. Please wait.
Published bySharyl Wilkinson Modified over 9 years ago
1
Python Crash Course Programming Bachelors V1.0 dd 13-01-2015 Hour 5
2
Good 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
3
Good 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).
4
Good programming practice Blocks and indentation Python 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.
5
Indentation 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
6
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: | | __abs__(...) | x.__abs__() abs(x) | | __add__(...) | x.__add__(y) x+y | | __coerce__(...) | x.__coerce__(y) coerce(x, y) | | __div__(...) | x.__div__(y) x/y |
7
Introduction 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 result smaller >>> if a < b: print ‘ok’ ok Comparison operators: == != > < >= <= is is not in not in Boolean operators: and or not
8
Membership and Identity Operators OperatorDescriptionExample inEvaluates 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 inEvaluates 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: OperatorDescriptionExample isEvaluates 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 notEvaluates 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:
9
Operators Precedence OperatorDescription **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 operators is is notIdentity operators in not inMembership operators not or andLogical operators The following table lists all operators from highest precedence to lowest.
10
Introduction to language - conditionals General format: if : elif : else: >>> 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'
11
Introduction 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] = ?
12
Introduction to language - loops General format: while : # loop test # loop body else: # optional else # 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 a 5
13
Introduction to language - loops for in : else: # optional, didn't hit a break >>> 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
14
Introduction 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
15
Introduction to language - Loop control The 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
16
Documentation 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
17
Good programming Code layout –4 spaces indentation –continue sensibly # Aligned with opening delimiter foo = 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', )
18
Good 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)
19
Good 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.' ) """Triple double quotes""“ '''\ Triple single quotes\ ''‘
20
Good programming White space Yes: spam(ham[1], {eggs: 2}) No: spam( ham[ 1 ], { eggs: 2 } ) Yes: if x == 4: print x, y; x, y = y, x No: if x == 4 : print x, y ; x, y = y, x Yes: i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) No: i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b)
21
Introduction 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__
22
Introduction 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 error will throw an exception, which you can then handle. So the equivalent code in Python would look like...
23
Introduction to language - exceptions Try-except x = 0.0 try: ratio = y/x except ZeroDivisionError: print 'Divisor = 0' The try/except syntax has the advantage that what you want to do appears first, you don’t have to read past a lot of error trapping code to find 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
24
Introduction to language - exceptions Try-except import sys try: untrusted.execute() except: # catch *all* exceptions e = sys.exc_info()[0] write_to_page( " Error: %s " % 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
25
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.
26
Unittests 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()
27
Testing 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)
28
Introduction to language End
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.