Working with variables
Working with numbers
You can use variableA memory location within a computer program where values are stored. to store numbers.
pocket_money = 20
The variable 鈥榩ocket_money鈥 is used to store how much pocket money you have. Right now you have 拢20.
As well as using fixed numbers in calculations and storing the answer in a variable, we can also use variables within the calculations themselves. In this example, the instruction uses the variable 鈥榤oney_in_bank鈥 to calculate the answer and then stores the answer in a variable called 鈥榯otal_money鈥.
total_money = money_in_bank + 10
The variables represent any valueA numerical amount denoted by a specific term, eg the value of x is 10. we choose to assign to them.
Consider this PythonA high-level programming language. (3.x) program:
>>> money_in_bank = 20
>>> total_money = money_in_bank + 10
>>> print(total_money)
30
The first line stores the value 20 to the variable 鈥榤oney_in_bank鈥. Since the computer knows that 鈥榤oney_in_bank鈥 has the value 20, it can calculate the value of 鈥榯otal_money鈥 and store it. Once calculated, the value of 鈥榯otal_money鈥 can be printed to the screen.
Once a value is stored, all sorts of mathematical operations can be performed on the variables:
>>> money_in_bank = 20
>>> total_money = money_in_bank + 10
>>> print(total_money)
30
>>> cost_of_holiday = 150
>>> left_to_pay = cost_of_holiday - total_money
>>> print(left_to_pay)
120
Working with text
A variable can hold a number, but it can also hold a piece of text. Just one letter is called a characterA single letter, digit or punctuation mark.. More than one character is called a stringA sequence of characters often stored as a variable in a computer program. These characters can include numbers, letters and symbols. .
A text variable works in the same way as a number variable, with a couple of differences:
- text variables hold characters (letters, digits, punctuation)
- the data in text variables is placed in quotes
- arithmetic calculations cannot be performed on text variables
Consider the following Python (3.x) program that uses strings:
>>> message = "Hooray! It's my birthday!"
>>> print(message)
Hooray! It's my birthday!