Variables and constants Flashcards
What are variables and constants used for?
To store values in algorithms and programs
Use of identifiers (2), long and short versions, and limitations (2)
A name given to a variable or constant
Identifiers describe the data being stored
- short identifiers are easier to spell correctly each time they are used
- long identifiers can be used if they are more descriptive (e.g. firstName)
They can’t be the same as reserved words such as print or while
They must be consistent throughout the program
Difference between variables and constants
Variables can change while a program is running
Constants must not change while a program is running
assignment statements
Variables are assigned in assignment statements using the = symbol
They can be changed while the program is running, e.g. variable = variable * 2
Constants
They are assigned using:
const (name) = (value) const Pi = 3.142
They are used in calculations
Camel case and snake case
Ways to format identifiers
In camel case, lower and upper case characters are used
The first word can be lower case (or not):
variableName
VariableName
FirstName
pricePerKilo
PricePerKilo
In snake case words are linked with an underscore:
first_name
price_per_kilo
Assignments
The association of a piece of data with a variable or constant
Often done as an input
Variables can be output to the user and will print the value rather than the identifier:
print(name) doesn’t output the word ‘name’
Identify the variables that are used in this algorithm and state the purpose of each. [6]
length = input ("Enter the length of the rectangle.") width = input ("Enter the width of the rectangle.")
area = length * width
print(area)
The variables are:
length, width, and area
length and width store values that are input by the user, and area stores the result of multiplying the length by the width
A student is writing an algorithm that allows a user to input their marks for five tests and then calculate the average mark.
List suitable variables that can be used in the algorithm. [1]
result1, result2, “, “, “, average