Transcript Slides

Continuing Professional Development in Computer Science for
Secondary School Teachers
Python 3.5.x Programming
Key Stages 1-5 (OCR/AQA)
Keith Dures and Frans Coenen
Session-1
1
Course Introduction
• To introduce procedural programming concepts
supported by computational thinking
• To develop programming skills in Python 3.5.x to
support commands to control
– Sequence (I/O, variables, constants, types of data,
arithmetic on data, converting data)
– Selection (If-else, function calls)
– Iteration (For, While, nesting)
– Compound Types (tuples, lists)
– Compound Types-II (Dictionaries)
– Files (I/O, strings, exceptions)
2
Session-1 Introduction –Sequence
• Environment
– editor (IDLE), interpretation, execution, debugging
• Representing algorithms as structured code
• Techniques for coding: I/O, variables, constants, types
of data, arithmetic on data, converting data
• Analysis and design of programs – structured
development based on incremental development
3
Programming Constructs
• Python v3.x is not compatible with v2.x
– Python code must be interpreted to execute
– Easier to type using IDLE (Integrated Environment)
• Note: Python is case sensitive
• Programming Constructs (3 basic types)
– Sequence
• print statements and input statements
– Selection (branching)
• if, if…else, break, continue statements
– Iteration (repetition)
• while and for statements
• Constructs apply to ‘data types’
4
Data Types
• Strings (collection of characters)
• There is no ‘char’ type in Python
• Numeric (Integer, Float)
• There is no ‘longint’ or ‘double’ type in Python
• Compound (Lists, Tuples, Dictionaries, etc)
• Equivalent to the ‘array’ type
5
Output using print()
Strings Using the print() function
• MUST have parentheses.
• Strings enclosed in single or double quotes (should
use a consistent ‘house style’).
• By default the print function outputs, left justified,
exactly what is between the quotes.
Style-1
print (‘Hello World’)
Style-2 is the course
‘house style’
Style-2
print (“Hello World”)
Any amount of spaces placed between words will also be output
6
Output using print()
Strings with
Escape Sequences
• Escape Sequences
can be used to
control output by
allowing special
characters to be
‘escaped’
• Use a \ character
followed by a symbol
or character
• \t for a single tab
• \n for a newline
Example-1 String Output
print (“Hello World”)
Hello World
---------------------------print (“\tHello World”)
Hello World
---------------------------print (“Hello\n” “World”)
Hello
World
---------------------------print (“Hello” “\nWorld”)
Hello
World
---------------------------# print a blank line
print()
---------------------------How to use comments
7
Input using input() and Output using print()
Strings
• input() function MUST have parentheses and halts
execution until user enters data and presses return key
• Need a variable to hold the input
– Data is assigned to the variable with ‘=‘
– Don’t use reserved words for variable names
Example-2 String Input and Output
userName = input(“Enter Your Name: “)
test1
‘=‘ is the assignment operator
print (“Hello”,userName)
It ISN’T the ‘equals operator’ (==)
Hello test1
There are no spaces in the brackets: The comma is a
‘separator’. It will put a space in the output for us
8
Sequence Exercise-1_Menu
I/O String
• Exercise-1: I/O; save
a) Write a program to
output on screen a menu
as shown right.
b) Add a message to output
the option the user has
selected.
Main Menu
--------D:
Division
M:
Multiplication
A:
Addition
S:
Subtraction
X:
Exit
Enter an Option:
9
Input using input() and Output using print()
Numbers
• Numeric input is in string format.
• To convert string to integer use int(input())
• To convert string to float use float(input())
Example-3 Numeric I/O
age_Now = int (input ("Enter your age in years: "))
21
age_In_Ten_Years = (age_Now + 10)
print ("Age in a decade:",age_In_Ten_Years)
Age in a decade: 31
---------------------------------------------------------#constant declaration - capitals remind not to change it
LENGTH_OF_METRE = 100
print (LENGTH_OF_METRE,”cm”)
100 cm
10
Session 1
Numbers Operations
•
•
•
•
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/, //, %)
– / is Integer (‘true’) division: x/y gives float result
– // is Floor division: x//y gives integer result if both
integer; truncated float if one or other or both float
– % is Modulo: x%y gives remainder (e.g. 10/3 = 1)
• Exponent (**): e.g. 3**2 = 9
• Equality (==) Not the same as the assignment operator (=)
11
Arithmetic
• Addition (+) and Subtraction (-)
Example-4 Addition and Subtraction
#addition: user input not shown for clarity
num1 = int(input(“Enter first num: “))
num2 = float(input(“Enter next num: “))
answer = (num1+num2)
print (“Sum =“,answer)
#subtraction: user input not shown for clarity
num1 = float(input (“Enter first num: “))
num2 = float(input(“Enter next num: “))
answer = (num1-num2)
print (“Result =“,answer)
12
Arithmetic cont.
• Multiplication (*) and Exponent (**)
Example-5 Multiplication and Exponent
#multiplication: user input not shown for clarity
num1 = int(input (“Enter first num: “))
num2 = int(input(“Enter next num: “))
answer = (num1*num2)
print (“Product =“,answer)
---------------------------------------------------------#exponent: user input not shown for clarity
num1 = int(input(“Enter first num: “))
num2 = int(input(“Enter next num: “))
result = (num1**num2)
print (“Solution =“,result)
13
Arithmetic cont.
• True division (/), Floor division (//)
Example-6 Division giving integer and float
#True division – answer always a float
num1 = int(input(“Enter first num: “))
10
num2 = int(input(“Enter next num: “)
3
result = (num1/num2)
print (“Solution =“,result)
Solution = 3.3333333333333335
Field width is 18
---------------------------------------------------#Floor division – answer is truncated integer if both
integer, else truncated float
result = (num1//num2)
print (“Solution =“,result)
Solution = 3
14
Sequence Exercise-2_floatingBarge
I/O and Arithmetic
Develop and implement a Python program which, given a barge defined in terms of
inputs for length(L), breadth(B) and height(H), outputs the associated draft.
Breadth(B)
weight of iron = 1.06kg per square metre
surface area = (2 * height) * (length + breadth) + (length * breadth)
mass of barge = surface area of barge * weight of iron
draft = mass of barge / (length*breadth)
15
I/O Numbers Operations
• Division Modulo (%) – outputs the remainder
Example-7 Modulo Division (%)
#integer modulo
Can be used as test for divisibility:
c = 10
if x%y = 0 then x is divisible by y
d = 3
print(c%d)
1
--------------------------------------------------------#float(decimal) modulo
e = 7.5
f = 2.4
print(e%f)
0.30000000000000027
16
Random Number Generation
• To generate series of random numbers a common equation used is:
Ni+1 = (KxNi) % M
where K and M are constants, Ni is the current term (random number) and Ni+1 is
the following term (remember % is the modulo operator).
• The equation requires a start term (N0), often referred to as the seed, after which
subsequent terms can be generated. To ensure realistic operation of the equation
appropriate values for K and M are also required.
• If N0=3, K=5 and M=4 all the terms will be equivalent to 3 ((5x3) % 4 = 3).
Theories exist on the best choice of values for K. In M. Skansholm (1997) it is
suggested that: K = 5^5 = 3125 and M = 2^13 = 8192; and a seed with an
odd number value within the range of 1..M-1 (i.e. 1..8191).
• This will then produce a series of "random" numbers within the range 1 and 8191.
If we wished to produce random numbers between say 0..100 or 0..10 or 0..1 we
would have to apply appropriate corrections:
100/M
or
10/M
or
1/M
17
Random Number Generation
User Seeded
Example-8 User-seeded random number generation
#Sess1_Example8_user_Seed.py
#User seeded random number generation
#generates one single random number on each execution
#INITIALISE
#ref Skansholm, M., set CONSTANTS
K = 3125
M = 8192
#INPUT
# N is the 'seed' provided by the user
N = int(input("Enter a number: "))
5
#CALCULATION
random = (K*N)%M
#OUTPUT
print (random)
7433
Note: The design on
previous slide outputs a
series of random
numbers. This code
outputs a single number
18
Sequence Exercise-3_Random
• Execute Sess1_Example8_user_Seed.py
• Input various integers and examine the output
• Note: No sample solution provided for this
exercise
19
Importing Modules
• Python comes with pre-built “modules” (classes).
• We can import these and call the functions that they contain.
• Functions are called using a dot operator.
Example-9 Import Modules (Classes)
#import the math module – all functions come with
import math
num = int(input(“Enter a number: “))
16
it
#use the sqrt function from within the math module
answer = math.sqrt(num)
print(answer)
4.0
print (math.pi)
3.141592653589793
dot operator for module.function
20
Importing Modules cont.
Example-10 Import Modules (Classes)
#import the math module – all functions come with it
import math
num = float(input(“Decimal number: “))
16.2
print(math.floor(num))
16
589793
------------------------------------------import time
myTime = time.time()
print (myTime)
1474543974.867878
21
Random Numbers Continued.
• We can use the system clock to generate a seed for our number generator
Example-11 Import Modules (Classes)
import time
t = time.time()
#truncate with .floor to produce integer in range 1 to 100
Seed = math.floor((t-math.floor(t))*100)
Example if t=34.56789:
Seed = math.floor((34.56789-34)*100) = 56
22
Sequence Exercise-4_Random
• Amend Sess1_Example8_user_Seed.py to generate a
random number using the system clock instead of
user input: Save it as Sess1_Exercise-4 .py
• Hints:
• INITIALISE – replace K and M with import time and
import math
• INPUT – use the time.time code from Example-11
• CALCULATION – replace ‘random’ with the seed
calculation in Example-11
• OUTPUT – replace print(random) with print (seed)
23
Simulate throwing a single dice
Import random module with randint function
#Throw a single dice to output a random number within
a given range (usually 1 to 6)
import random
#set the maximum number to be generated
max_Number = 6
#use the randint function from module random generates numbers from 1 to 6 inclusive
dice_Throw = (random.randint(1,max_Number))
#output
print (dice_Throw)
24
Sequence Exercise-5_dice
I/O and Import
a) Write a program to allow
a single user to throw
two dice, one after the
other
b) Add the total of the two
dice and output this back
to the user
c) Hints: import random;
don’t cheat and set the
random range as 1-12!
Pseudocode
1. Initialise variables
1.1 var max = 6
1.2 total = 0
1.3 die_1, die_2 = 0
2. Input (from system)
2.1 die1=random(1,max)
2.2 die2=random(1,max)
3. total = die1 + die2
4. print total
25
Standard Functions
• Some functions are available as standard and do not
need to be imported, e.g., len - returns the length of its
string argument, does not work on integer input
Example-12 Standard Function - len
nums = input("Enter some numbers: ")
74982
string input - we did not use ‘int’ to convert it
print(len(nums))
5
-----------------------------------------course_Name = input("Enter course: ")
Computing
print(len(course_Name))
9
26
Sequence Exercise-6_len
• Write code to prompt for entry, in the
following order:
• a) Your name
• b) Your office number (or make it up)
• c) Your mobile number (as an integer type)
• After each input, output the length of the
input. What’s wrong with (c)?
27
Formatted Output Using ‘.format’
{:value}.format(value)
• The format function is used with print() to control
how output is displayed
Example-13 Formatting
stud_Id=123
#output number 123 as an integer(d) in a field width of 5 spaces
print (“Student number{:5d}”.format(stud_Id))
format field
Student number
123
This is the ‘argument’ in
between ( ) to be passed to
the format field in between { }
Two spaces in front of number 123 as it takes up
three of the 5 five spaces in the output format
28
Formatted Output cont.
Example-14 Formatting
#students paying for a school trip
#input student Id and amount paid
sId = int(input(“Enter student id: “))
sPay = float(input(“Enter payment: “))
#pass arguments by position. sId is first in
argument list so is passed to {:5d} and sPay is
second in argument list so is passed to {:5.2f}
print (“Id{:5d},has paid {:5.2f}”.format(sId,sPay))
29
Sequence Summary
• Sequence operations (input, print) run once
• Users can input ANY data type other than the
one prompted for – so we have to trust the
user to enter a number if asked and hope they
don’t enter a string etc
• Sensible prompts can help, and sometimes
the output (especially numeric) may need to
be formatted to be useful and understood
• Selection constructs help control user I/O
30