1/16
[ BBC Bitesize 'Computational thinking, algorithms and programming ⇢ Programming techniques page 6-7 ]
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Program
Sequences of instructions for a computer.
Subroutines
A small program that is written within a main program to carry out a specific function.
Code for Defining a Subroutine:
def subroutineName(parameterOne, parameterTwo)
Types of Subroutines:
procedures
functions
Procedures
A section of computer code that performs a specific task by taking in parameters.
Functions
A section of computer code that performs a specific task and returns a value by taking in parameters.
Benefits of Subroutines:
usually small in size → easier to write, test, debug and understand
can be saved separately as modules and used again in other programs → this saves time
used repeatedly at various points → the code only has to be written once, resulting in shorter programs
Built-in Functions:
int - converts strings or floats into integers
str - converts a number into a string
asc - finds the ASCII number of a character
Libraries
A collection of pre-written, tested functions that extend the functionality of a language. stored in a separate file.
Function Example:
def add(a, b)
result = a + b
return result
sum = add(5, 3)
print(sum)
Local Variables
Variables that are defined within a subroutine and can only be used in said subroutine.
Global Variables
Variables that are defined outside a subroutine but are valid both in and out of subroutines.
Parameters
Variables listed inside the parentheses when defining a subroutine. They act as placeholders for the values that will be passed to the subroutine when it is called.
Arguments
The actual values passed to the subroutine when it is called. They provide the subroutine with the data it needs to operate on.
Code for Random Number Generator (Integer):
import random
randomNumber = random.randint(1,100)
print(randomNumber)
Code for Random Number Generator (Float):
import random
#generates a random float between 0 and 1 (inclusive)
randomFloat = random.uniform(0, 1)
print(randomFloat)
Code for Random Number Generator (Arrays):
import random
items = [1, 2, 3, 4, 5]
#generates a random item from list
randomItem = random.choice(items)
print(randomItem)