programming python quick intro for schools
DESCRIPTION
python progamming quick intro for schoolsTRANSCRIPT
Computing and programming workshop
Dan BowenCarine Jacquel
What is a computer program?
A computer program is simply a set of instructions to tell a computer how to perform a
particular task.
Picture: Charles Babbage – Difference engine
Binary - Machine Code
Binary 0110 0001 0110 0010
Machine Code001273 05 04 001273 06 04
Assembly code
To add two numbers the (binary) machine code could be : 001273 05 04
Assembly code meant that the intial programmers had an interface for the binary
A typical assembler line could be ADD 05 04
Interpreter and Compiler
A programmer writes a program in a high level language (Source Code)
This is interpreted into the bytes that the computer understands (Object code – often called binary code, machine code)
The interpreter has a couple of names, one being the interpreter and the other being the compiler.
Structured programs
Edsger Dijkstra came up with several key principles that all structured programs require:
• Sequences• Branches• Loops• Modules
Top Tip – Get the kids to use flowcharts before hand. This is good practice and helps for
program design.
Sequences
Step 1 Step 2 Step 3
Branching
Step 1 Test condition
Path 1
Path 2
Q : Can you think of a situation you
might use a branch?
True
False
Loops
Repeated Steps
Test Condition
Q : Can you think of a situation you might use a Loop?
The art of debugging
• Making errors (syntax, runtime, semantic)
• Resolving errors
Our first program
>>> print “Hello World”
What happens if you type
>>> Print “Hello World”
A quick pocket calculator….
>>> print 5 + 6
Functions + - * /
Try it… have a go at some more calculations. When doing maths remember
BIDMAS (Brackets, Indices, Division, Multiplication and Subtraction)
>>> print ((6 * 5) + (7 - 5)) / (7 + 1)
Integers and real numbers
>>> print 5/2
>>> print 5/2.0
Modulo >>> print 7/2 3 >>> print 7%2 1
What is an integer?
What is a real number?
Joining strings and numbers
>>>print 'The total is: ', 23+45
Activity : Have a Play
This is calledConcatenation
Combining text and numbers
>>> print "The sum of %d and %d is: %d" % (7,18,7+18)
• %s - for string • %x - for hexadecimal number • %0.2f - for a real number with a maximum of 2 decimal
places • %04d - pad the number out to 4 digits with 0's
>>>import sys
• Some Python programs will use extra ‘objects’ and ‘functions’
• An example of this is import.sys
An example of this could be >>>import sys>>>sys.exit()
Variables
>>> q = 7 # q is now a number >>> print q 7
>>> q = "Seven" # reassign q to a string >>> print q Seven
Good practice - A note about comments
Poor:v = 3600 # this is an integer set at 3600s = t*3600 # t is time
Better:v = 3600 # 3600 is num of secs in an hour s = t*3600 # t holds elapsed time in hours, so convert to secs
Text variables
With single quotes: 'Here is a string'
With double quotes: "Here is a very similar string"
With triple double quotes: """ Here is a very long string that can if we wish span several lines and Python will preserve the lines as we type them..."""
Manipulating strings
• There are several sub functions on each programming language that allow you to treat text like and array and do things such as – find a sub string– join two strings (concatenation)– copy one to another
<<< More examples>>> print 'Again and ' + 'again' Again and again
>>> print 'Repeat ' * 3 Repeat Repeat Repeat
>>> print 'Again ' + ('and again ' * 3) Again and again and again and again
We can also assign character strings to variables: >>> s1 = 'Again ' >>> s2 = 'and again ' >>> print s1 + (s2 * 3) Again and again and again and again
Integers
Operator Example Description
M + N Addition of M and NM - N Subtraction of N from MM * N Multiplication of M and N
M / NDivision, either integer or floating point result depending on the types of M and N. If either M or N are real numbers(see below) the result will be real.
M % N Modulo: find the remainder of M divided by N
M**N Exponentiation: M to the power N
Not sensible maths but vital in programming
>>> x = 42 >>> print x >>> x = x + 1 >>> print x
Python also has a shortcut for this>>> x += 1 >>> print x
Boolean OperatorsOperator Example Description Effect
A and B AND True if A,B are both True, False otherwise.
A or B ORTrue if either or both of A,B are true. False if both A and B are false
A == B Equality True if A is equal to BA != BorA <> B Inequality True if A is NOT equal to B.
not B Negation True if B is not True
Boolean (or Logical) Operators
Using IDLE or text editor
# File: firstprogram.py print "hello world" print "Here are the ten numbers from 0 to 9\n0 1 2 3 4 5 6 7 8 9" print "I'm done!" # end of file
Notepad, IDLE or any text editor can be used for this….
IDLE – All in one solution
Integrated DeveLopment Environment
Allows you to edit and run programs
ActivityCreate a NEW program Run it (F5)
FOR loops
>>>for i in range(1,11):… print i # must be indented
What do you think this code does?
>>>for i in range(1,13): ... print "%d x 12 = %d" % (i, i*12)
While loops (if we don’t know the number of iterations)
>>> j = 1 >>> while j <= 12: ... print "%d x 12 = %d" % (j, j*12) ... j = j + 1
Nested loops
>>> for multiplier in range(2,13): ... for j in range(1,13): ... print "%d x %d = %d" % (j,multiplier,j*multiplier)… print “------------” # this separates the tables
Other loops
• do-while - Same as a while but the test is at the end so the loop always executes at least once.
• repeat-until - Similar to above but the logic of the test is reversed.
• GOTO, JUMP, LOOP etc Mainly seen in older languages, these usually set a marker in the code and then explicitly jump directly to that marker.
Good practice tip – Add some style############################# # This is my first program# Author: Dan Bowen# Date: 27/02/2013# Version: Draft 1 ''' This program is a simple starter# program to help learn python############################### # Log: Added a variable to fix the counter 28/02/2013 DB# File created 27/02/2013################################
import sys,Print”Hello World”
Talking to the user
>>> resp = raw_input("What's your name? ") >>> print "Hi, %s, nice to meet you" % resp
Have a play with this
The Input() function
multiplier = input("Which multiplier do you want? Pick a number ") for j in range(1,13): print "%d x %d = %d" % (j, multiplier, j * multiplier)
Input is clever and tries to evaluate the type of data such as integers (numbers) which can then be used to calculate things.
However….>>>multiplier = int(raw_input("Which multiplier do you want? Pick a number "))
>>>for j in range(1,13): ... print "%d x %d = %d" % (j, multiplier, j * multiplier)
Input() can be used to delete files etc….so often it's better to stick to raw_input() and convert the string into the data type you need using Python's built in conversion functions.
Branching
A classic example. What does this program do?
10 PRINT "Starting at line 10" 20 J = 5 30 IF J < 10 GOTO 50 40 Print “Hello World" 50 STOP
If Statements to branch
import sys # only to let us exit print "Starting here" j = 5 if j > 10: print "This is never printed" else: sys.exit()
Combining Logical elements and IF’s save time
if value > maximum: print "Value is out of range!“else if value < minimum: print "Value is out of range!" ----------------------------------if (value < minimum) or (value > maximum): print "Value is out of range!"
Chaining IF Statements
if price == 100: print "I'll take it!" else: if price > 500: print "No way Jose!" else: if price > 200: print "How about throwing in a freemouse ?" else: print "price is an unexpected value!"
What does == represent?What would happen if 200 and 500
were switched?
Multi function IFmenu = """ Pick a shape(1-3): 1) Square 2) Rectangle 3) Triangle """ shape = int(raw_input(menu)) if shape == 1: length = float(raw_input("Length: ")) print "Area of square = ", length ** 2 elif shape == 2: length = float(raw_input("Length: ")) width = float(raw_input("Width: ")) print "Area of rectangle = ", length * width elif shape == 3: length = float(raw_input("Length: ")) width = float(raw_input("Width: ")) print "Area of triangle = ", length * width/2 else:print "Not a valid shape, try again"
A little bit on modules
The idea of programming with modules is to allow the programmer to extend the built in capabilities of the language. It packages up bits of program into modules that we can 'plug in' to our programs.
Some examples
• pow(x,y)
• To find out the variables within a module>>> import sys >>> dir(sys)
Have a play with the modules on the following slide
Module name Description
sys Allows interaction with the Python system: exit() - exit! argv - access command line arguments path - access the system module search path ps1 - change the '>>>' python prompt!
os Allows interaction with the operating system: name - the current operating system, useful for portable programs system - execute a system command mkdir - create a directory getcwd - find the current working directory
re Allows manipulation of strings with Unix styleregular expressions search - find pattern anywhere in string match - find at beginning only findall - find all occurences in a string split - break into fields separated by pattern sub,subn - string substitution
math Allows access to many mathematical functions: sin,cos etc - trigonometrical functions log,log10 - natural and decimal logarithms ceil,floor - ceiling and floor pi, e - natural constants
time time(and date) functions time - get the current time (expressed in seconds) gmtime - convert time in secs to UTC (GMT) localtime - convert to local time instead mktime - inverse of localtime sleep - pause program for n seconds
random random number generators - useful for games programming! randint - generate random integer between inclusive end points sample - generate random sublist from a bigger list seed - reset the number generator key
FilesAssume we have a file called menu.txt This contains
spam & eggs spam & chips Spam & spam
Open and reading the file
inp = file("menu.txt","r") inp.readlines(): print line inp.close()
A simple file copy
# Create the equivalent of: COPY MENU.TXT MENU.BAK # First open the files to read(r) and write(w)inp = open("menu.txt","r") outp = open("menu.bak","w") # read file, copying each line to new file for line in inp: outp.write(line) print "1 file copied..." # Now close the files inp.close() outp.close()
Another file exampleimport time# Create daily menu based on MENU.TXT # First open the files to read(r) and write(w) inp = open("menu.txt","r") outp = open("menu.prn","w") # Create todays date string today = time.localtime(time.time()) theDate = time.strftime("%A %B %d", today) # Add Banner text and a blank line outp.write("Menu for %s\n\n" % theDate) # copy each line of menu.txt to new file for line in inp: outp.write(line) print "Menu created for %s..." % theDate # Now close the files inp.close() outp.close()
Program design
• Comments• Variable names• Program names• Block structure – Python important!
A word on Object Orientation
Most languages these days are object orientated. This enables code to be reused and
saves on developmental costs.
Object Orientation in Python – complex classes
Classes are complex user defined ‘objects’
>>>class Address: ... def __init__(self, Hs, St, Town, Zip):... self.HsNumber = Hs ... self.Street = St ... self.Town = Town ... self.ZipCode = Zip ... >>> Addr = Address(7,"High St","Anytown","123 456") >>> print Addr.HsNumber, Addr.Street
OO using the class
Essentally we import the module, create an instance of Spam, assigning it the name mySpam and then use mySpam to access its operations and data:
Points to remember• Programs control the computer • Programming languages allow us to 'speak' to the computer at a level that is closer to
how humans think than how computers 'think' • Error messages are nothing to be scared of, read them carefully, they usually give a clue
as to why you got them. • But it's only a clue... if in doubt check the lines immediately before the reported line.• Python does math almost the way you'd expect • To get a fractional result you must use a fractional number • You can combine text and numbers using the % format operator • IDLE is a cross platform development tool for writing Python programs. • Comments can make programs clearer to read but have no effect on the operation of
the program • Variables can store intermediate results for later use • FOR loops repeat a set of commands for a fixed number of iterations. • WHILE loops repeat a set of commands until some terminating condition is met. They
may never execute the body of the loop if the terminating condition is false to start with. • Use if/else to branch • The else is optional • Multiple decisions can be represented using a Case or if/elif construct • Boolean expressions return True or False
Thank you