Variables - Lakelands Computing

Title
Go to content
Variables in Python
In programming a variable is somewhere where you can store a single piece of data. More accurately it is a named, reserved space in the computers memory where you can store a single piece of data.

Python variables are quite clever, they automatically detect data types based on the data that is stored in them. This means you don't have to state the data type when you create them.

In Python you create a variable and assign it a value (store a piece of data in it) at the same time, for eg:
  • a variable called name with the string "Bob" in it.
  • a variable called age with the integer 18 in it
  • a variable called height with the float 1.78 in it
  • name = "Bob"
  • age = 18
  • height = 1.78
As you can see you can do basic Maths with variables such as:
  • adding them together (line 5)
  • increasing the number stored in a variable - line 13 and line 17 (these do exactly the same thing, the += on line 17 is just a short hand version of score = score +  on line 13)
  • I've used adding, but you can use - to subtract, / to divide and * to multiply
  • For more complex maths use the math module - see this section on RealPython.com for more on this

You can also use variables with strings (text) - see lines 19 onwards and this page on working with variables for more details
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content