Lesson 9 +10 XP

Variable Names

Variable Names

Names can be almost anything, but Python has a few rules.

The rules

  • A name can contain letters, digits, and underscores.
  • It must start with a letter or an underscore.
  • It cannot start with a digit.
  • It cannot contain spaces.
  • It cannot be a reserved word like if, while, class, for.
myvar = 1       # ok
my_var = 2      # ok
_my_var = 3     # ok
myVar2 = 4      # ok
2myvar = 5      # SyntaxError: cannot start with a digit
my var = 6      # SyntaxError: no spaces allowed

Case matters

myVar, MyVar, and myvar are three different variables.

Naming styles (pick one and stay consistent)

  • Camel case: myVariableName
  • Pascal case: MyVariableName
  • Snake case: my_variable_name (recommended by the Python style guide)

Reserved words

Python has about 35 reserved words you can't use as names, including if, else, def, return, class, import, True, and None.

Be descriptive

total_price is a better name than tp or x1. Good names make code self-explanatory.

TL;DR

  • Letters, digits, underscores; start with a letter or underscore.
  • No spaces, no leading digit, no reserved words.
  • Python is case-sensitive.
  • Snake_case like my_variable is the recommended style.