Category: Implementation (Computational constructs)

National 5 – SDD Predefined Functions

So today we were looking over predefined function. For the N5 course we have to be aware of RANDOM, ROUND, & LENGTH.

The RANDOM function picks an integer between two values.

import random
number=random.randint(1,20) # random(StartValue,EndValue)
print(number)

The ROUND function rounds a real number (floating point) to a fixed number of decimal points.

a=1.2 # 1
b=2.6 # 3
c=2.5 # 2
d=3.5 # 4
e=3.453444354

print(round(e,2)) # round(valueToRound,NoOfDecimalDigits)

The LENGTH function displays the number of characters in a String or the length of an Array.

name="Stratton was here"
numbers=[1,2,3,4,2,3,4,6,4,3,2,43]
print(len(name))
print(len(numbers))
print(numbers)

for index in range(len(numbers)):
    print(numbers[index])

for index in range(len(name)):
    print(name[index])

 

Logical Operators

AND

Both expressions must be True for the result to be True

Expression 1 Expression 2 Result
False False False
False True False
True False False
True True True

 

OR

Either expression must be True for the result to be True

Expression 1 Expression 2 Result
False False False
False True True
True False True
True True True

 

NOT

The result is the opposite of the Expression

Expression Result
True False
False True

 

 

Higher – Random Number Array Function

The class was asked to create a function that generated 100 number dice throws and stored them in an array.

This function is used to create an array of random integers. The size of the array and the magnatude of the values is set when the function is called.


def randomNumbers(size,min,max):
    # creates an array of (size) random numbers between min and max
    import random
    numbers=[]
    for loop in range(size):
        numbers.append(random.randint(min,max))
    return numbers

rndNumbers=randomNumbers(100,1,6)

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

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.