Creating a Legal Variable

We choose the names of our variables ourselves. But, there are some rules around creating a legal variable (a name we’re allowed to use).

Variable names may:

  • Use upper-case and lower-case letters
  • Use numbers
  • Use underscore characters (an underscore is the _ character)
There are rules to creating a legal variable

If we name our variables like this, we won’t have any problems:

>>> my_variable = 6
>>> string6 = 7
>>> YourVariable = 88

There are also things we can’t do. When naming variables, we cannot:

  • Use spaces
  • Start with a number

Look at what happens if we try to create an illegal variable:

>>> my variable = 6
  File "<stdin>", line 1
    my variable = 6
       ^^^^^^^^
SyntaxError: invalid syntax

>>> 2Variables = 6
  File "<stdin>", line 1
    2Variables = 6
    ^
SyntaxError: invalid decimal literal

Some Examples

ExampleLegal?Notes
ayesLower-case is fine
time2goyesNumbers are fine
100waysnoA variable cannot start with a number
AyesUpper-case is fine
fun_timesyesUnderscores are allowed and recommended where there would normally be a space
fun timesnospaces are not allowed
FunTimesyesCapitalizing is fine
_countyesStarting with an underscore is fine
fun!noCharacters other than numbers, letters, and underscores are not allowed