Variables & Constants
Every variable and constant needs a name, called an identifier. Python only accepts identifiers that follow its rules, so a name that breaks them is a syntax error and the program will not run at all.
An identifier may contain letters, digits and underscores. It cannot contain spaces, cannot start with a digit, and cannot be a Python keyword such as if, for or while. Keywords are words Python reserves for its own instructions, so Python rejects them as names.
| Identifier | Valid? | Reason |
|---|---|---|
bus_number | Valid | Uses letters and an underscore, and starts with a letter. |
bus number | Invalid | Contains a space. |
2nd_score | Invalid | Starts with a digit. |
while | Invalid | Is a Python keyword. |
Identifiers are case-sensitive: total, Total and TOTAL are three separate names, and creating one does not create the others. You must also spell a name consistently. If you assign a value to lap_time, then write laptime later, Python treats the second name as a new, undefined identifier rather than the one you meant.
The same rules apply whether the name is for a variable or a constant.
score = 15
print(Score)Output:
NameError: name 'Score' is not defined (line 2) Edexcel GCSE Computer Science · Variables & Constants