Variables and names
Basics7 min readLesson 2 of 8
A variable is a name that refers to a value. You create one with =, putting the name on the left and the value on the right. The name can then stand in for the value wherever you use it. Good names make a program easier to read months later, for you and for anyone else who opens the file.
name = 'Ravi'
age = 15
print(name)
print('Age:', age)2.1 How assignment works
The right side is calculated before the left side receives the result. score = score + 1 means take the current score, add one, then store the new number under the same name. Names are case sensitive: total, Total, and TOTAL are three different names.
2.2 Naming rules
- A name starts with a letter or an underscore.
- Letters, digits, and underscores can follow the first character.
- Spaces and hyphens are not allowed.
- Keywords such as
if,for, andclassare reserved.
score = 10
score = score + 5
print(score)
label = 'level'
print(label, score)2.3 Common mistake
Using a name before it has a value breaks the code. print(total) works only after a line like total = 0 has run. A misspelled name raises NameError when Python reaches it. Read the error for the name Python could not find and compare it with the assignment above. Reassigning a name to a different kind of value is allowed, but keep the purpose of the name clear.
left = 'tea'
right = 'coffee'
left, right = right, left
print(left, right)2.4 Practice
- Write a small profile with
name,city, andagevariables. - Print a sentence that uses all three.
- Change
ageon a new line and print the sentence again.
For longer variable names, use underscores, as in favourite_subject. Write constants such as MAX_SCORE in capitals to signal that the value should stay fixed.
