Predefined Functions

A predefined function is a function that has already been written in the programming language and can be used by the programmer. A function will return a value that can be stored in a variable or sometimes in a conditional statement.

There are three predefined functions you need to be bale to use at National 5

Random (randint)

The random function is used to generate a random number. In Python there are a various different random functions but the one we will use is the randint() function

When generating random numbers you need to import the random library.  The random.randint() function will return a random integer between a lower and upper value.

Python Example

This code will generate a random integer between 1 and 100.

Choosing items from an array at random

If you need to choose a random item from an array what you could to is pick a random integer that is between 0 and the last element in the array. You could then use this to perform whatever operatio it is you need.

The yellow shaded areas in the structure diagram to left show that the random number is being chosen between 0 and 19 ( there are 20 elements in  the array.

Example Python Code to choose random item

Random Integer Tutorial Video

SDD 7.4 Random Int Function.mp4

Rounding to decimal places

You may have to round your answers.  To do this you will have to use the round() function.

If rounding a value to 3 decimal places use the following code:

This would round the value to 3 decimal places (4.727 )and assign it to the variable roundedVal.

Or you can use a variable instead of a value:

This would round the value to 3 decimal places (4.727 ) and assign it to the variable roundedVal.

If you want to round to the nearest number you use the round function without any number of places.

.5 will be rounded towards the nearest even number. Don't worry you won't be penalised because of this.

The variable roundedAnswer would now store the integer value 4

Rounding to Decimal places Tutorial Video

SDD 7.2 PreDefined Functions Decimal Places.mp4

Length Function

The len() function has a few different uses:

String Length

The len() function is used to display the length of a variable. So if you run the code below you will see that it will tell you the amount of characters including spaces.

Code to use the len function on a string

Length of an Array

The len function can also be used with arrays to find out how many items are in it.

The code below will automatically know that there are 6 items in the array as the code len(numbers) will return 6 which is the length of the array.

Use in Input Validation

It could be used for input validation – for example to ensure that a password is long enough.

Demonstration of using the len function with a String for Input Validation

Len Function Tutorial Video

SDD 7.3 Len Function.mp4

Demonstration of how to use the len function to return the length of a string or the length of an array