Think of a labelled jar on a kitchen shelf. The label stays the same, but you can empty the jar and fill it with something else whenever you like. Programs work the same way: rather than repeating a raw value such as a price or a username everywhere, you give it a name once and refer to that name from then on. When the value changes, every line that reads the name sees the new value.
Names also make code readable. total_price tells a reader far more than the bare number 49.99 sitting in the middle of a calculation.
Example
score = 0 # create the variable
score = score + 10 # update it using its old value
player = "Ada"
print(player, "has", score, "points") # Ada has 10 points
In Python you create a variable simply by assigning to it. Some languages want an extra keyword first: JavaScript uses let or const, PHP prefixes every name with $, and Java requires a declared type, as in int score = 0;.
Naming and types
Most languages allow letters, digits and underscores in names but forbid a leading digit, and names are usually case-sensitive, so Score and score are two separate variables. Choose names that describe what is stored.
Languages disagree on whether a variable has a fixed type. In Java, a variable declared as int can only ever hold whole numbers. In Python, JavaScript and PHP the same name can hold a string now and an integer later, because the type belongs to the value rather than to the name.
Variables vs constants
A constant is a name whose value should not change once it is set, such as const TAX_RATE = 0.2 in JavaScript. Python has no enforced constants; programmers signal the intent by writing the name in capitals and simply not reassigning it.
Keep going
- Practise assigning and printing values in the Python editor.
- Work through the basics in the programming fundamentals course.
- See how a function receives values as its inputs.
Last updated