Category: Software Design & Devlopment

N5 – Input Validation

Today we looked at the following problem

Write a program which will allow a user to input only a number in the range 0-100. An error message will be output if the number is invalid.

The program will output a message when the number input is valid (after the loop for checking the number).

We then worked through Analysis, Design, Implementation and Testing of the program.

Analysis

Input – a number

Process – check number is between 0 and 100

Output – a message about the numbers validity

Design

We looked at all three design methodologies and created designs in our jotter.

Pseudocode

  1. Declare Integer Number
  2. Get Number from user
  3. While Number < 0 OR Number > 100
  4.     Display “Sorry that number is not valid”
  5.     Get number from user
  6. End While
  7. Display “That is a valid number”

Flowchart

Structure Diagram

Implementation in Python


number=0 # declare number as type integer
number = int(input("Please enter a number from 0 - 100 "))
while number < 0 or number > 100:
    print("Sorry that number is not valid")
    number = int(input("Please enter a number from 0 - 100 "))
print("That is a valid number")

Testing

We tested the code with Normal, Extreme and Exceptional test data.

N5 – Input Process Output

Leading on from the work we did last term and this week. We created a program to solve the calorie counter problem.


Analysis

Inputs

  • calories in porridge
  • calories in toast
  • calories in marmalde
  • calories in coffee

Process

  • add all calories and store in total

Output

  • The total number of calories in breakfast

Design

  1. Get the number of calories in porridge
  2. Get the number of calories in of toast
  3. Get the number of calories in of marmalade
  4. Get the number of calories in of coffee
  5. Total = Porridge + toast + marmalade + coffee
  6. Display the total number of calories

 

Higher – Input Validation (Revision)

We use the standard algorithm input validation to check that the user is entering a value that is expected by the program. In the example below our function is used to check that the entered integer is between a max and min value.

 

def getValidInt(fMin,fMax):
    print("Please enter a number between",str(fMin), "and",str(fMax))
    number=int(input())
    while number<fMin or number>fMax:
        print("Sorry try again")
        print("Please enter a number between",str(fMin), "and",str(fMax))
        number=int(input())

    return number

def main():
    min=-100
    max=100
    
    number1=getValidInt(min,max)
    number2=getValidInt(1,20)
    print(number1,number2)

main()

The function follows the AREA standard algorithm, that is Ask Repeat Error Ask. so

  1. Ask for valid number
  2. Repeat While number not valid
  3.     Display Error
  4.     Ask for valid number

Too remember this mnemonic easier think Jonathan Ross for step 2, as in Python we would use a While.

The code above makes use of local variables as well as formal and actual parameters. Can you spot them?

Higher – Procedures – Horse Hands

A computer program stores the names, ages and height (the height of horses is measured in ‘hands’ – for example, 16) of fifteen horses in a riding school. The user of the program will be asked to select a horse by entering a maximum age and height of the horse they wish to ride. The data for the fifteen horses will be used to provide the user with a list of suitable. A horse is suitable if its age and height are both less than or equal to the values entered by the user.

To solve the program above we first of all have to break the program into smaller steps.

  1. A computer program stores the names, ages and height (the height of horses is measured in ‘hands’ – for example, 16) of fifteen horses in a riding school.
  2. The user of the program will be asked to select a horse by entering a maximum age and height of the horse they wish to ride.
  3. The data for the fifteen horses will be used to provide the user with a list of suitable. A horse is suitable if its age and height are both less than or equal to the values entered by the user.

We then have to look at how data is passed inside the program

This allows us to create a program that uses procedures to solve the problem.

def storeHorses():
    names=["Bob","Frank","Sue"]
    ages=[4,5,6]
    heights=[12,13,14]
    return names,ages,heights

def getSearch():
    maxAge=int(input("What is the max age you want to ride > "))
    maxHeight=int(input("What is the max height you want to ride > "))
    return maxAge,maxHeight

def displayHorses(names,ages,heights,maxAge,maxHeight):
    for horse in range(3):
        if ages[horse]<=maxAge and heights[horse]<=maxHeight:
            print(names[horse],ages[horse],heights[horse])

def main():
    #set up up variables
    names=[]
    ages=[]
    heights=[]
    maxAge=0
    maxHeight=0
    
    names,ages,heights=storeHorses()
    maxAge,maxHeight=getSearch()
    displayHorses(names,ages,heights,maxAge,maxHeight)

main()

Higher – Rock Paper Scissors – Solution

So when we implemented the code we got something like this

#Mr Stratton

import random

#set up variables
random.seed
object=["Rock","Paper","Scissors"]
playerChoice=""
computerChoice=""
winner=""

#Get players choice
playerChoice=object[int(input("Rock - 1\nPaper - 2\nScissors - 3\n"))-1]

#Get computer choice
computerChoice=object[random.randint(0,2)]

#get winner
if playerChoice=="Rock":
    if computerChoice=="Paper":
        winner="Computer"
    if computerChoice=="Scissors":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        
if playerChoice=="Paper":
    if computerChoice=="Scissors":
        winner="Computer"
    if computerChoice=="Rock":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        
if playerChoice=="Scissors":
    if computerChoice=="Rock":
        winner="Computer"
    if computerChoice=="Paper":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        

    
#display winner
print("\n"*10)
print("Player threw",playerChoice)
print("Computer threw",computerChoice)

if winner=="Player":
    print("Player is the winner")
    
if winner=="Computer":
    print("Computer is the winner")
    
if winner=="Draw":
    print("Its a draw")


However, although it does follow the design from yesterday it isn’t very effcient.
Can you see a way to make it more effient?

#Mr Stratton

import random

#set up variables
object=["Rock","Paper","Scissors"]
playerChoice=""
computerChoice=""
winner="Draw"

#Get players choice
playerChoice=object[int(input("Rock - 1\nPaper - 2\nScissors - 3\n"))-1]

#Get computer choice
computerChoice=object[random.randint(0,2)]

#get winner
if playerChoice=="Rock":
    if computerChoice=="Paper":
        winner="Computer"
    elif computerChoice=="Scissors":
        winner="Player"

        
elif playerChoice=="Paper":
    if computerChoice=="Scissors":
        winner="Computer"
    elif computerChoice=="Rock":
        winner="Player"

        
elif playerChoice=="Scissors":
    if computerChoice=="Rock":
        winner="Computer"
    elif computerChoice=="Paper":
        winner="Player"

        
else:
    print("Error in player choice")
    
#display winner
print("\n"*10)
print("Player threw",playerChoice)
print("Computer threw",computerChoice)
if winner=="Player":
    print("Player is the winner")
elif winner=="Computer":
    print("Computer is the winner")
else:
    print("Its a draw")

Read more

Python – Thonny

I know that some of you have struggled to get Python working at home, so let me introduce you to Thonny.

Thonny is a Python IDE for beginners, it has Python built in so no need for a seperate install. It has a lot of cool features that you may find useful. I am going to demo a few features (the following text is from the Thonny homepage http://thonny.org/ )

No-hassle variables.

Once you’re done with hello-worlds, select View → Variables and see how your programs and shell commands affect Python variables.

Variables table

Simple debugger. Just press Ctrl+F5 instead of F5 and you can run your programs step-by-step, no breakpoints needed. Press F6 for a big step and F7 for a small step. Steps follow program structure, not just code lines.

Stepping through statements

Step through expression evaluation. If you use small steps, then you can even see how Python evaluates your expressions. You can think of this light-blue box as a piece of paper where Python replaces subexpressions with their values, piece-by-piece.

AH – 2D Array Recap

It took us a little while in class today to remember how 2D arrays work, so I thought I might go over it.

A 2 dimentional (2D) array is an array of arrays. So [[1,2,3,4],[5,6,7,8],[9,10,11,12]] is a 3 item array where each item is a 4 item array. This can be written as

[[1,2,3,4],

[5,6,7,8],

[9,10,11,12]]

You might notice that it looks like a grid (or matrix), this is where the 2D comes in to the name. In python we can create the array and assign it.

2d
2D Array in Python

In the code above you can see the the individual elements of the 2D array are accessed using a pair of square brackets [][]. Using the image below we can see the [1][2] is number 7, as demonstrated in the program above.

grid2d

We can use a loop to display each value in the 1st column.

Using a for loop with a 2D array.
Using a for loop with a 2D array.

Or a nested for to display each item in each array

Nested for traversing 2D array.

N5 Python – Introduction

add2numbersOur 1st Python program makes use of a number of new constructs and variables.

# – Internal Commentary, anything after the # on the same line is ignored by the translator

= (Assignment) – values are assigned to the variables using an equals sign.

input() –  a string is captured from the keyboard using the input() function

int() – this function changes the datatype of the given variable to an integer (Whole number)

Expression – The expression is the right hand side of the =, this is evaluated and any calculations performed, the results are then assigned to the variable on the left hand side of the equals

print() – This function displays a string. The “,” is used to concatenate strings and add a space between them.