Values and Variables · practice
Choose Helpful Variable Names
Python lets you choose most
Compare these two versions:
x = "Saturday"
y = "library"
day_of_week = "Saturday"
destination = "library"
Both versions can work, but the second tells you what each
The rules Python enforces
A variable name can contain letters, numbers, and underscores (_), with two important restrictions:
It cannot begin with a number.
It cannot contain a space, hyphen, or other punctuation.
These are valid names:
name = "Robin"
score2 = 18
price_per_ticket = 12.5
These are not valid:
2nd_score
ticket price
ticket-price
Python is also case-sensitive. score, Score, and SCORE are three different names.
The style Python programmers usually use
For ordinary variables, Python programmers normally use lowercase words separated by underscores:
favorite_color = "green"
number_of_guests = 4
This style is called snake case because the underscores connect the words along the line.
A good beginner rule is: choose the shortest name that still explains the value. number_of_guests is helpful. the_number_of_guests_who_are_coming_today is harder to read than it needs to be.
Deep dive
A few words have a special purpose in Python and cannot be used as variable names. They are called keywords. Examples include for, class, and True.
You will meet several keywords later. If Python rejects a name that otherwise looks valid, its error message may tell you that the word is reserved.
Which is the clearest valid Python name for the price of one ticket?
Improve the starter program
The starter program uses the vague names x and y.
Rename them so:
xbecomesday_of_week.ybecomesdestination.
Update the two print instructions to use the new names. The output must remain:
Saturday
library
When you rename a variable, update every place that uses it. If an old name remains in a print instruction, Python will report a
Press Run first. When the output is still correct and the new names are in place, press Submit.
Task
Rename the
xbecomesday_of_weekybecomesdestination
Update the print instructions too. The output should still be:
Saturday
library