DB section has been updated to add some SQL code.
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
Round
Length
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.
This code will generate a random integer between 1 and 100.
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.
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
The len() function has a few different uses:
It can be used to find the length of a string
It can be used to find the amount of items in an array
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.
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.
It could be used for input validation – for example to ensure that a password is long enough.
Demonstration of how to use the len function to return the length of a string or the length of an array