brixton library technology initiative week1 recap

Post on 14-Apr-2017

179 Views

Category:

Self Improvement

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Welcome to the Brixton Library Technology Initiative

(Coding for Adults)

ZCDixon@lambeth.gov.uk

BasilBibi@hotmail.com

January 23rd 2016

Recap Week 1

Recap of Week 1 Topics

• Functions• Modules• Long division //• Boolean Expressions• Relational Operators • Conditional Statements

Functions

• reusable pieces of code.• header and body.• header starts with def ends with ‘:’• Can take parameters.• indentation.• return

Functions

• Functions may return a value using the keyword return and / or have a side effect (e.g., print, modify some data structure).

• To evaluate a function call, replace the function's parameters in the body of the function by their associated values in the call and execute the body of the function.

• Indentation consists of whitespace formed by blanks, tabs, and newlines.

• Incorrect indentation = errors.

• Examples - http://tinyurl.com/p49tekp http://tinyurl.com/ja8hlgq

Function Errors - http://tinyurl.com/jxbnn54

Functions – Scope Of Variables

• ‘Scope’ means rules about which variables are ‘visible’ and updatable.

• age = 52 # age is ‘global’ - can be seen everywhere in your program

• def increment() : birthYear = 1963 age = age+1 # a local copy of age is taken and updated

print age # printing the local copy of age

• birthYear is not visible outside the function – only has scope inside increment() – said to have ‘local‘ scope

Functions – Modifying Global variables

• We can modify a global variable inside a function if we declare the local variable age to be the global one

• age = 20

def f() : global age age += 1 print age

Long division //

• In normal infant school maths 49 / 10 = 4 remainder 9

• We can do the same with python using

// for the whole numbers part (‘quotient’) and % for the remainder

• # get the tens and ones digits of a number• num = 49• tens = num // 10 # 4 remainder 9• ones = num % 10 # 4 remainder 9

Built in functions

Modules

• Useful libraries of Python.• Examples - math, random.• Modules can be accessed using

the import statement.• Don’t forget to import or you will get errors.• Use google to find useful modules.

• math Examples - http://tinyurl.com/jv2wmfs

Very Useful Built in Modules

• In no particular order:• collections• csv - always use this to read/write CSV files, don't try and roll

your own methods, it'll end in tears• datetime• math - try and use these functions rather than the global ones,

they're faster when you import them into the global namespace• Re - regular expressions• string - I rarely see this used, but it's very handy• tempfile - always use this to create temporary files• unittest – used to write simple small tests.

3rd Party Modules – Top 20• 1. Requests

The most famous http library. It’s a must have for every python developer writing web applications.

• 2. ScrapyIf you are involved in webscraping then this is a must have library for you. After using this library you won’t use any other.

• 3. wxPythonA gui toolkit for python. I have primarily used it in place of tkinter. You will really love it.

• 18. noseA testing framework for python. It is used by millions of python developers. It is a must have if you do test driven development.

• http://pythontips.com/2013/07/30/20-python-libraries-you-cant-live-without/

Conditional Statements

• If ( abc == 1 ) : # do thiselif ( abc == 2 ) : # do this insteadelif ( abc == 2 ) : # you can have any number of these elifselse : # do this if the others are not true

• Each if and elif tests a Boolean Expression (see slides later)

• Examples - http://tinyurl.com/zaue823

Conditionals – consider order and test for edge cases

Order and simplify your conditionals to aid reading

age = 12

if( age > 12 and age < 20 ) : print "Teenager"elif ( age <= 12 ) : print "Kid"else : print "Adult“ # this is easier to make sense of if( age < 13 ) : print "Kid"elif (age < 20 ) : print "Teenager"else : print "Adult"

This has a subtle bug - prints Adult

age = 12

if( age > 12 and age < 20 ) : print "Teenager"elif (age < 12 ) : print "Kid"else : print "Adult "

Conditionals – nesting

You can put conditionals inside other conditionals – called nesting.

profession = "Programmer"language = "Python"

if( profession == "Programmer"): if( language == "Python" ) : print "Pythonic!" else: print "There is always time to learn a useful skill!"else : print "You are missing out on a world of fun"

Conditionals – avoid variable names that are negatives

Variable names that are negatives become hard to reason about especially if they are bools

not_a_programmer = Falseif( not_a_programmer ) :….

is_a_programmer = TrueIf( is_a_programmer ) :….

not_a_programmer = Falseif( not not_a_programmer ) :….

This is a lot easier to reason about at 3am on a prod support ;)

This is insane - I need a truth table just to work out what this means.

Conditionals – beware nesting hell

if () :if() : if() : else :if() :else :

elif() : else :elif() :else :

To resolve this you might need to completely rewrite it (‘refactor’).

Remember good code is easy to read and make sense of.

Make sure you write tests that prove each outcome.

One technique is to use functions to make sections easier to read and test – we can nowwrite a simpler test that tests just callFunc1()

if () :if() : callFunc1()

elif() : else :elif() :else :

Boolean Expressions• The constants True and False of the type bool.

• These constants can be combined to form Boolean expressions via the logical operators and, or, and not.

• The and of two Boolean expressions is True if both of the expressions are True.

• The or of two Boolean expressions is True if at least one of the expressions is True.

Boolean short-circuiting

Boolean expressions short-circuit. They stop evaluating as soon as possible.

age = 12if( age > 12 and age < 20 ) : print "Teenager"elif (age < 13 ) : print "Kid"else : print "Adult“

As soon as age > 12 is evaluated to False the and age < 20 is skipped because Python already knows the entire expression can never be true

Try to take advantage of this it will make your code faster and easier to read.

Boolean Expressions• The constants True and False of the type bool.

• These constants can be combined to form Boolean expressions via the logical operators and, or, and not.

• The and of two Boolean expressions is True if both of the expressions are True.

• The or of two Boolean expressions is True if at least one of the expressions is True.

A helpful way to work out boolean expression outcomes

Set out all of the input conditions , in this case (P,Q) and gradually build up the complexity.

Be careful not to miss any test conditions. There are always 2n where n is the number of inputs.

e.g. In the above, we have 2 inputs (P,Q) therefore the number of test conditions is 22 = 4

With 3 inputs P, Q and R it would be 23 = 8

Truth Tables

P Q P and Q P or Q not PT T T T FF T F T TT F F T FF F F F T

P Q R P and Q and RT T T TF T T FT F T FF F T FT T F FF T F FT F F FF F F F

Relational Operators• The values of two arithmetic expressions can be

compared using the operators

• These return either True or False

If( a < 2 and b < 12 and c != 14 )

If( a < 2 and b < 12 and c != 14 )

== != < > <> <= >=

Relational Operators with StringsCan compare strings too.

# This prints Zeb Test

name = "Basil“

if( name < "Apple" ): print "Apple"elif( name < "Zebra" ): print "Zeb test" else : print “We are here“

String comparison uses lexicographical ordering .

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

In this case B < Z

ASCII Table# prints Zeb test

name = “Basil"

if( name < "Apple" ): print "Apple Test"elif( name < "Zebra" ): print "Zeb test" else : print "We are here"

# prints We are here

name = “basil"

if( name < "Apple" ): print "Apple Test"elif( name < "Zebra" ): print "Zeb test" else : print "We are here"

top related