Variables
A variable name is the label you choose for a variable in your program. Python only accepts names that follow a few rules, and there are some good habits that make your programs easier for other people to read.
lap-time means lap take away time.3laps is rejected, but laps3 is accepted.if, class and None already have a job in Python, so using one as a name would confuse the interpreter.wins and Wins are two completely separate variables, so a stray capital letter creates a new variable instead of updating the one you meant.| Name | Valid? | Reason |
|---|---|---|
lap_time | yes | letters and an underscore only |
lapTime | yes | letters only, with no spaces or symbols |
3laps | no | starts with a digit |
lap time | no | contains a space |
lap-time | no | the hyphen is read as a minus sign |
class | no | it is a keyword |
Pick a meaningful name that describes the value stored. homeTeamGoals tells a reader far more than h, so another programmer can tell what it holds without tracing through the whole program. Meaningful names also make your own code easier to check when you come back to it.
When a name needs more than one word, join the words in one of two styles: camelCase, where the first word is lower case and each new word starts with a capital letter with no spaces (shotSpeed), or underscores (shot_speed). Both are accepted by Python, but choose one style and keep to it, so the code reads consistently from top to bottom.
# one style throughout: underscores between words
book_title = "The Lost Robot"
total_pages = 128
pages_read = 42
pages_left = total_pages - pages_read
print(pages_left)Output:
86