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-2
1
Sessions 1 to 6 - Overview Reminder
• To introduce procedural programming concepts
supported by computational thinking
• To develop programming skills in Python 3.5.x to
support commands to control
1. Sequence (I/O, variables, constants, types of data,
arithmetic on data, converting data)
2. Selection (If-elif-else function calls)
3. Iteration (For, While, nesting)
4. Compound Types (tuples, lists)
5. Compound Types-II (Dictionaries)
6. Files (I/O, strings, exceptions)
2
Session2 – Learning Objectives
•
•
•
•
•
•
Selection construct in Python
Selection syntax (if-elif-else)
User-defined functions (with no parameters)
Efficient coding
Testing strategies
Problem solving approaches (computational
thinking)
3
Selection Construct
• Selection executes selected lines of code while
ignoring other lines by applying a ‘test condition’
that evaluates to ‘True’ or ‘False’
• If condition = ‘True’, then execute indented code
immediately following the condition line (the colon)
• If condition = ‘False’, then ignore indented code
following the colon and either:
– Pass completely out of the selection construct
– Pass to an else statement
– Pass to an elif statement
Selection Construct
• If evaluates to Boolean values True, False
• Must end with ‘:’ on the condition line
• Must have indented actions
• Uses Boolean operators
<
>=
<=
>
<> (!=)
==
Mathematics
‘equal to’
• Uses logical operators
– and - evaluates two tests and executes the indented
statements if both tests are True
– or – evaluates two tests and executes the indented
statements if any one of the two tests is True
– not – sometimes easier to test for the negative condition
Selection Syntax
• The following slides (up to Exercise-1) show the various
forms selection can be coded
• We can test against numeric values and string values
• Using IDLE, indentation, colour, etc. is automatic
– Be careful to keep to the indentation – try not to alter it
• Example-3, Example-4 and Example-4a all do the same
thing – they indicate if input is positive or negative
• Example-4a is more efficient than Example-4
• But Example-4 adds an output to show input was zero –
is this what you wanted?
• Decide what you want before you code
Selection: (numeric) if – elif - else
Example-1
If
Example-2
If – else
one entry, one exit
one entry, two exits
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
else:
print ("Number is not negative")
Example-3
If – elif – else
Example-4
Nested if
one entry, three exits
one entry, three exits
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
elif (x > 0):
print ("Number is positive")
else:
print ("Number is zero")
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
else:
if (x > 0):
print(“Number is positive")
7
else:
Selection: (numeric) if – elif - else
Example-4 (again)
Nested if
Example-4a
Nested if
one entry, three exits
one entry, two exits
#test for –ve, +ve, 0 is default
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
else:
if (x > 0):
print(“Number is positive")
else:
print (“Number is zero")
#change of Boolean operator
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
else:
if (x >= 0):
print(“Number is positive”)
8
Selection: (string) if – elif - else
Example-5
If – single statement
person = input(“Nationality? “)
if person == “french”:
print (“Capital is Paris”)
Example-6
If – multiple statements
#execute all indented statements when True
person = input(“Nationality? “)
if person == “french”:
print (“Capital is Paris”)
print (“Country is France”)
Most boolean operators, ‘<‘, etc do not normally apply to
string comparison (unless using ASCII etc conversion)
Selection: (string) if – elif - else
Example-7
If with no elif
person = input(“Nationality? “)
if person == “french”:
print (“Capital is Paris”)
if person ==“irish”:
print (“Capital is Dublin”)
This statement executes in sequence after the first one.
If ‘”french” is true from the statement above it, it doesn’t
need to execute: Use an elif to handle this
All lines of code indented after the colon
and before the next else or elif will be
executed
Example-8
If , elif and else
a)
person = input(“Nationality? “)
if person == “french”:
print (“Capital is Paris”)
print (“Country is France”)
elif person == “irish”:
print (“Capital is Dublin”)
b)
#captures a non-valid response
person = input(“Nationality? “)
if person == “french”:
print (“Capital is Paris”)
elif person == “irish”:
print (“Capital is Dublin”)
print (“Country is Eire”)
else:
print (“Not French or Irish”)
Selection: (string) if – elif – else: and, or
Combinations of Boolean operators and logical
operators
Example-9
if - or
person = input(“Nationality? “)
if person == “french” or person ==“French”:
print (“Capital is Paris”)
elif person ==“irish” or person ==“Irish”:
print (“Capital is Dublin”)
else:
print (“Neither French nor Irish”)
Example-10
if -and
#don’t always need elif
age = int(input ("age? "))
born_In = input ("Country? ")
if age >= 18 and born_In == "UK":
print ("Can vote")
else:
print("Not 18 and/or not UK")
Two tests: To be able to vote, age >=18 must be True
and born in the UK must be True
Selection: if – elif – else
•
•
•
•
A 1-year-old dog is equivalent to a 14-year-old human;
A 2-year-old dog is equivalent to a 22-year-old human;
Every year over 2-years-old is equivalent to 5 years human
Find the human age of the dog (needs three tests: age is 1, 2, or >2)
Example-11
several elif’s
Example-12
several elif’s with else
dog_Age = int(input ("Dog\'s age?: "))
if dog_Age == 1:
print ("14 years human")
#no dog lives past 20 years old
dog_Age = int(input("Dog\'s age?: "))
if dog_Age == 1:
print ("14 years human")
elif dog_Age == 2:
print ("22 years human")
elif dog_Age == 2:
print ("22 years human")
elif dog_Age >2:
human_Age = (22+(dog_Age-2)*5)
print (human_Age)
elif dog_Age >2 and dog_Age <=20:
human_Age = (22+(dog_Age-2)*5)
print (human_Age)
else:
print (“Too old”)
Selection Exercise-1
Objective: Importance of an
effective test strategy to
check all paths through the
program
a) Execute
Session2Exercise1.py
b) Select an option and run
the test cases against it
c) Test cases: -1, 0 , 1
Main Menu1
---------A:
If
B:
If-else
C:
If-elif-else
D:
If Nested
X:
Exit
Enter an Option:
13
Selection Exercise-1 Review
• This is a poor example of programming
• It is inefficient
• We have to cater for input of uppercase and
lowercase
• All the code is written within the main body
making it harder to maintain and read
• User-defined functions (def) should be the
way to program for efficiency, code re-use and
readability
User-defined functions: def
() means no parameter passing involved
def ifStatement():
print ("Option-1: if")
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
def ifElseStatement():
print ("Option-2: if-else")
x = int(input("Enter an integer: "))
if (x < 0):
print ("Number is negative")
else:
print ("Number is not negative")
print ("Main Menu")
print ("---------")
print ("1:
If")
print ("2:
If-else")
option = input("Enter an Option: ")
if option == "1":
ifStatement()
elif option == "2":
ifElseStatement()
2: After being called,
execution transfers to def
3: When finished,
execution transfers back
to the ‘caller’
1: def ifStatement is ‘called’
Selection Exercise-2: Barge
Objective:
• User-defined functions to
improve efficiency
• Code re-use
a) Execute
Session2Exercise2.py
a) Amend the barge.py code
to test if the barge will
capsize (draft > height)
Main Menu2
---------1:
Barge
X:
Exit
Enter an Option:
16
Selection Exercise-2_Support
Barge Algorithm
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)
If draft > height
then barge may
capsize
17
Selection Exercise-3: Dice
Objective: Using functions to
improve efficiency
a) Execute
Session2Exercise3.py
b) Amend def dice. After
outputting the total, if
they roll a double-six,
inform them and tell
them to roll again. Tell
them to pass the dice if
not a double-six
Main Menu3
---------1:
Barge
2:
Dice
X:
Exit
Enter an Option:
18
Selection Exercise-3_Support
Dice - double-six
a) The pseudocode for the
dice.py amendment can be
used as shown
Pseudocode
1. Initialise variables
1.1 die1 max = 6
1.2 die2 max = 6
1.2 total = 0
1.3 die1, die2 = 0
2. Input (from system)
2.1 die1=random(1,max)
2.2 die2=random(1,max)
3. Output
3.1 total = die1+die2
3.2 print total
3.3 if die1 ^ die2 = 6
then
3.3.1 print
19
‘throw again’
Selection Exercise-3_Support
Dice: Random Number Generation
#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)
20
Selection Exercise-4: Leap
Objective: Problem solving
Use of Boolean variables
a) Execute
Session2Exercise4.py
b) Swap the def Leap code
to the one given in
Example14. Run the tests
amending the output
(something like? “1700 is
a leap year: Answer =
False”)
Main Menu4
---------1:
Barge
2:
Dice
3:
Leap
X:
Exit
Enter an Option:
21
Selection Exercise-4_Support
Leap Year - definitions
#Input a year as nnnn and determine if a leap year
Every year that is exactly divisible by four is a leap year, except for years
that are exactly divisible by 100, but these centurial years are leap years
if they are exactly divisible by 400. For example, the years 1700, 1800,
and 1900 are not leap years, but the years 1600 and 2000 are.[5]
https://en.wikipedia.org/wiki/Leap_year
A calendar year of 366 days, February 29 ( leap day) being the additional
day, that occurs every four years (those whose number is divisible by
four) except for century years whose number is not divisible by 400. It
offsets the difference between the length of the solar year (365.2422
days) and the calendar year of 365 days
http://www.dictionary.com/browse/leap-year
22
Selection Exercise-4_Support
Leap Year: Thinking 1 & 2
#Thinking 1 (Structured English)
a) Leap year is divisible by 4;
b) Leap year is divisible by 4, not divisible by 100;
c) Leap year is divisible by 4 and 100 and 400
-----------------------------------------------------#Thinking 2 (Pseudocode)
1. If divisible by 4 then execute 2 else execute 5
2. If divisible by 100 then execute 3 else execute 4
3. If divisible by 400 then execute 4 else execute 5
4. Leap Year
5. No Leap year
23
Selection Exercise-4_Support
Leap Year: Thinking 3
Truth Table
#Three tests producing one of two outcomes
Three tests = (23) = 8 possibilities
Year
(nnnn)
Test-1
Test-2
Test-3
(n/4) =0? (n/100)=0? (n/400)=0?
Leap year?
nnnn
n
n
n
N
nnnn
n
n
y
N
nnnn
n
y
n
N
nnnn
n
y
y
N
nnnn
y
n
n
Y
nnnn
y
n
y
Y
nnnn
y
y
n
N
nnnn
y
y
y
Y
24
Selection Exercise-4_Support
Leap Year: Thinking 4
#Some possibilities are invalid (illogical)
Year
(nnnn)
Test-1
Test-2
Test-3
(n/4) =0? (n/100)=0? (n/400)=0?
Leap year?
nnnn
n
n
n
N
nnnn
n
n
y
INVALID
nnnn
n
y
n
INVALID
nnnn
n
y
y
INVALID
nnnn
y
n
n
Y
nnnn
y
n
y
Y (INVALID)
nnnn
y
y
n
N
nnnn
y
y
y
Y
25
Selection Exercise-4_Support
Leap Year: Application
Example-13 Sample Solution
Leap = 1600, 2000, 2400, 400
No leap = 1700, 1800, 2100, 2200, 500
#Session2Example13.py
#Test for divisibility: if x%y=0 then x (dividend) is divisible by
y (divisor)
#modulo division outputs remainder. If remainder = 0 then numbers are
divisible: Solution derived from ‘Thinking 1 & 2’
year = int(input("Enter a year(nnnn): "))
if (year%4 == 0) and (year%100 != 0) or (year%400 == 0):
print ("Leap Year")
else:
print ("No Leap Year")
26
Selection Exercise-4_Support
Leap Year: Application
Example-14 Sample Solution
Same test data
#Session2Example14
#Use of a Boolean variable (holds ‘True’ or ‘False’ only)
#Can be used to improve readability
year = int(input("Enter a year(nnnn): "))
isLeapYear = ((year%4 == 0) and (year%100 != 0) or (year%400 == 0))
if isLeapYear:
print ("Leap Year”)
else:
print (“No Leap Year”)
27
Selection Exercise-5: Password
Objective:
Validating user input
a) Execute
Session2Exercise5.py
b) Write a program to
validate input for a
password. The password
is a combination of
characters and numbers,
minimum length = 5
Main Menu5
---------1:
Barge
2:
Dice
3:
Leap
4:
Password
X:
Exit
Enter an Option:
28
Selection Exercise-6: Hero
Objective: Using selection
effectively with testing
a) Execute
Session2Exercise6.py
Main Menu6
---------1:
Barge
2:
Dice
3:
Leap
b) Hero is a dragon-slayer with a shield
4:
Password
of 100 points and a sword of 100
Hero
points. When the sword strikes the 5:
dragon, 5 points are lost from the
X:
Exit
sword. When the dragon strikes the
shield, 10 points are lost from the
shield. The quest fails when either
the sword is below 80 points or the
shield is at 50 points or less
Enter an Option:
29
Selection Summary
• Selection operations (if, if-else, if-elif-else) run
once
• Users can input ANY data type other than the
one prompted for – so we have to trust the
user to enter a valid input
• 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