A variable is used to temporarily store a piece of data.
The '=' symbol is used to assign a value to a variable, in Python this is known as the assignment operator'.
For example:
In the code above the variable is called number1
and the value it is storing is 10. Variables can hold any type of data. Using variables makes it easier for people to understand what is going on.
For example:
Adding or subtracting values from variables
To add or subtract a value from a variable, use the following code:
Casting Variables
Python will automatically decide what type of data a variable should be, sometimes this isn’t right, therefore you will have to convert/cast variables to a different data type.
Integer
The program below will multiply a number by 5. When data is input from the user it will store it as a string. You will need to convert the variable number
to an integer
before performing a calculation. An example of how you do this is shown below:
Real / Float
The program below will ask the user to enter their weight in kilograms (this could be a decimal) and convert it to pounds. You will need to convert the variable kg
to a float
before converting it. An example of how you do this is shown below:
String
Using the program above, if you wanted to improve the print message so that it said Your weight in pounds is X
you would need to convert the variable pounds to a string
as it is currently a float
.
This is what would happen if you ran the code currently:
This is because the variable pounds is a float
and to be joined with a string in the print message it needs to be converted to a string
, the code is below:
Now when run the code it will work correctly:
Example program 1 - Water Tank Capacity Program
The code for the program below will allow the user to enter the height, width and depth of a water tank, then calculate and output the capacity.
When run in IDLE:
The code above rounds the variable capacity, to round a variable you use the round()
function. You write the name of the variable followed by the number of decimal places e.g. round(capacity,2)
.
Example program 2 - Cylinder Volume Program
The code for the program below will allow the radius and height of a circle, then calculate and output the volume and surface area.
When run in IDLE: