Brixton Library Technology Initiative Week0 Recap

Post on 17-Feb-2017

244 views 2 download

Transcript of Brixton Library Technology Initiative Week0 Recap

Welcome to the Brixton Library Technology Initiative

(Coding for Adults)

ZCDixon@lambeth.gov.uk

BasilBibi@hotmail.com

January 16th 2016

Week 0 Recap - RPSLP

Recap of Week 0 Topics

• Comments• Variables• Assignment• Operators• Statements• Expressions

# Comments# A comment starts with a #

# Very useful for you to focus your mind on the problem and # for the person who has to maintain your code

# Makes it easier to understand your program later – it might # surprise you but you will forget exactly how your own code works # especially if it’s complex or non obvious.

# if your code changes be sure to update your comments !# A stale comment (one that contradicts the code) is worse than no comment at all.

# 01232456789012345678901234567890123456789012345678901234567890123456789012# Try to make comment lines shorter than 50 characters per line. # It’s easier to read than very long lines of text.

# Anything after the # is ignored by python e.g. print "I could code like this." # and the comment after is ignored – use sparingly

# You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print "This will run."

What Are Variables?

• Variables are buckets that hold data.• They have a name.• Makes it easier to work with your data.

• print 3.141 * 100

• Intention of the above becomes clear when we use variables with meaningful names – we were calculating and displaying the circumference as this self documenting code shows:

diameter = 100PI = 3.141circumference = PI * diameterprint circumference

Variables : Valid Characters• You can use any letter, the special underscore character “_” and every number provided

you do not start with a number.

• 1stThingsFirst• _valid• notPoss-ible # python thinks this means notPoss - ible• *noWayMatey

• Make your variable names meaningful increases readability – self documenting code.

• a = 52• studentAge = 52• student_Age=52• dontmakeyourvariablehaveridiculouslylongnames = “!”

• dontMakeYourVariableHaveRidiculouslyLongNames = “!”

Naming Variables• Recommended reading – the Python Style guide

https://www.python.org/dev/peps/pep-0008/

• Examples of naming conventions.

• Single character names :• B

• lowercase• lower_case_with_underscores• UPPERCASE• UPPER_CASE_WITH_UNDERSCORES

• Throughout the standard library, the most common way to define constants as module-level variables is using UPPER_CASE_WITH_UNDERSCORES – hence PI in my previous example.

# CapWords, or CamelCase -- so named because of the bumpy look of its letters # This is also sometimes known as StudlyCaps.

• CapitalizedWords

# When using abbreviations in CapWords, capitalize all the letters of the abbreviation. # Thus HTTPServerError is better than HttpServerError.

• mixedCase # differs from CapitalizedWords by initial lowercase character!

• Capitalized_Words_With_Underscores # (ugly!)

Variables : Reserved Words• Must not be one of the reserved keywords.

• and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while yield

Assignment• Put some data into a variable.• “Setting a variable’s value“

• my_integer_var = 25• my_string_var = “Hello World”

Operators• They act on variables.• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

+ - * /

= += -= *= /=

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

and or not

Operator Precedence

• From latin praecedere "go before"

• PEMDAS"Please Excuse My Dear Aunt Sally".It stands for "Parentheses, Exponents, Multiplication and Division, Addition and Subtraction".

• BODMASB=brackets first O=orders(like power and square etc.,) D=division(/) M=multiplication(*) A=addition(+) S=subtraction(-)

Operator Precedence

• PE MD AS"Please Excuse My Dear Aunt Sally".Parentheses, Exponents, Multiplication . Division, Addition .Subtraction“.

• () a**2 a*a a/2 a+1 a-1

Operator Precedence

• PEMDAS"Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction“.

• 5 * 3 + 2 - 4• 13

• 5 * 3 + 2 - 4• 15 + 2 - 4• 17 - 4 • 13

Operator Precedence

• PEMDAS"Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction“.

• 5 * 3 + 2 - 4• 13

• Use brackets to force evaluation• 5 * ((3 + 2) – 4)• 5

Operator Precedence• Very few people remember operator precedence so use brackets to show exactly what

you mean.

• Everyone remembers that brackets come first so use them to force python to evaluate in the way you intend. This also makes your code easier to understand.

• mortgage_amount + arrears / years• 120 +12 /10• 121

• (mortgage_amount + arrears) / years• (120 + 12) /10• 13

• NB – because we are using int in the calculations we end up with the decimal places being discarded – “truncated“

• Truncation is explained later in this slide deck.

Python Primitive Types• These are the basic types of data you work with.

e.g. numbers, strings, true/false

• Numeric Types — int, long, float-5 0 1 2 3 etc

• String

• Boolean – True False

• A whole host of other built in types that we will cover later.

Python int• Whole numbers both positive and negative i.e Integers• Remember, integers do not have a decimal or fractional part

-5 0 1 2 3 etc

• 3.141 – this is not an integer it is a floating point number.

print type(42)<type 'int'>

• On a 64 bit machine running a 64 bit version of pythonsys.maxint = 9,223,372,036,854,775,807 = 264 – 1 9 * 1019

• On a 32 bit version of python2,147,483,647 = 232 -12*107

• Range –sys.maxint to sys.maxint

Python Integer “Rounding Down” - Truncation• Beware – if you use int or long in a calculation that yields a decimal you lose all of

the decimal places – a feature known as truncation.

• Python just drops the decimal places, it’s not really a rounding process it just discards the data.• Rounding is a different process that follows certain rules. The overall effect of truncation is the same as rounding

down.

• # should be 3.333… but python returns 3 # we have lost the 0.3333 part - it was discarded

• print 10 / 33

• # resulting is some subtle bugs• print (10 / 3) * 3

9

• Look at these further examples :• print (10 / 3) * 2• 6

• print (10 / 3) * 2.0 # the 10/3 part has already lost precision so this is 3 * 0.2• 6.0

• print (10 / 3.0) * 2.0 # now we get the decimal parts because 10/3.0 is 0.3333…• 6.66666666667

Rules for negative truncation: 3.3333 => 3-3.3333 => -4

Python long• Any Integer larger or smaller than int.

print type (sys.maxint+1) <type 'long'>

• Unlimited - actually limited to the amount of memory you have.• Absolutely huge numbers - truly mind boggling.

• e.g. 128 bytes = 1024 bits• 21024 =

`

179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477320753602

112011387987139335765878976881441662249284743063947412437776789342486548527630221960124609411945308

295208500576883815068234246288147391311054082723716335051068458629823994724593847971630483535632962

4224137216

• That number is 1.79*10308

• There are ‘only’ around 1080 atoms in the visible universe.

Python Float• Any number with a decimal place.• “Floating point”

print type(3.141)<type ‘float’>

• Again a huge range of numbers.

• Smallest sys.float_info.min (2.2250738585072014e-308) 2.2250738585072014 * 10 -308

• Largestsys.float_info.max (1.7976931348623157e+308).1.7976931348623157 * 10 308

Python Primitive Types• String – use double or single quotes to delimit the text.• Can contain double or single quotes inside.• Must match at the ends.

• “Mary had a little lamb, she also had some gravy”• ‘Mary had a little lamb, she also had some gravy’• “Mary had a ‘little’ lamb, she also had some gravy”• ‘Mary had a “little” lamb, she also had some gravy‘

• boolean – hold value for True or False • True and False are reserved words.• Type of boolean is ‘bool’

Statements• A statement is an instruction or command that Python will execute. • We have seen two kinds of statements so far : print and assignment.

• When you declare a print statement in your code, Python executes it.It puts characters on the screen.Assignment statements don't produce a result.

• A script usually contains a sequence of statements which are processed one at a time in the order they were written.

• For example, the script• print 1

x = 2 print x

• produces the output• 1

2 • Again, the assignment statement produces no output.

Expressions• An expression is a combination of values, variables, and operators that are the calculations or logic you

want to execute.

• 1 + 1 • b + c• PI * diameter

• Although expressions contain values, variables, and operators, not every expression contains all of these elements. A value all by itself is considered an expression, and so is a variable.

• 17 • x

• In a script, an expression all by itself is a legal, but it doesn't do anything. The following script results in nothing.

17 3.2 'Hello, World!' 1 + 1

Comments, Statements, Operators, Expressions, Variables, Assignment

• Let’s put it all together.• Remember a variable is also an expression.

• # Statement - it has an assignment using the operator of an expression (“Spooky”) to a variable (pet_name)

• This next line is a statement because of the print command.Note the expressions and variables

pet_name = “Spooky”

print “%s is %i in earth years , %i in dog years.” % (pet_name, age_earth_years, age_dog_years)

pet_name

7age_earth_years

6dog_aging_rate

*

pet_name

age_dog_years age_earth_years dog_aging_rate

=

=

=

= *

=

In CodeSkulptor

Note : line 8 uses the “line continuation” character ‘\’

http://www.codeskulptor.org/#user41_qHZ1pvOqLztPmGM.py

http://tinyurl.com/PythonExampleBLTI

The Modulus Operator %

• Gives the remainder of a division as an int

• print 12 % 5 2

%

Rock Paper Lizard Scissors Spock

Rock Paper Lizard Scissors Spock

Assign numbers to the 5 positions in the ring starting with zero.

Rock Paper Lizard Scissors SpockRearrange in outcome order:Make Rock zero.Work out all outcomes from Rock’s perspective.Put all of the opponents that rock’s will lose against on the

clockwise side.

Rock Paper Lizard Scissors SpockPut all opponents that rock can

beat on the anti-clockwise side.

Rock Paper Lizard Scissors Spock

Rock Paper Lizard Scissors SpockNow use the formula given to work out the outcomes for player1 as rock.

Score = (player1 – player2) % 5

Rock Paper Lizard Scissors Spock

Rock Paper Lizard Scissors Spock# A code templatescore = (player1 - player2) % 5If score == 0 :

# drawelif score==1 or score==2 : # player1 winselse : # player2 wins