Menu

Variables

Variable Names

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.

Rules for names

  • Use only letters, digits and underscores. A space or a symbol such as £ is not allowed, and Python reads a hyphen as a minus sign, so lap-time means lap take away time.
  • A name cannot start with a digit. 3laps is rejected, but laps3 is accepted.
  • A name cannot be a keyword. Words such as if, class and None already have a job in Python, so using one as a name would confuse the interpreter.
  • Names are case sensitive: wins and Wins are two completely separate variables, so a stray capital letter creates a new variable instead of updating the one you meant.
NameValid?Reason
lap_timeyesletters and an underscore only
lapTimeyesletters only, with no spaces or symbols
3lapsnostarts with a digit
lap timenocontains a space
lap-timenothe hyphen is read as a minus sign
classnoit is a keyword

Choosing good names

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

Practise this