Variables

Back to main page

Assignment

Variables in Python are assigned via =. As examples,

myString = "Aren't variables great?"
myInt = 40

Python is a left-hand assignment language, so the following is illegal syntax:

40 = myInt

Since Python is dynamically typed, one does not need to specify the types of variables. It possible to hint types, however.

Variable names, conventions, and keywords

In general, Python allows for the user to name the variables pretty much about anything they want, with a few exceptions. In particular, Python disallows variables from being named as any of the following keywords—words reserved for the Python language itself:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

This list was obtained from here.

As far as variable-naming conventions go, I personally prefer camelCase, but it is also common to see snake_case. In any case, you should pick a style you prefer and stick with it (unless you are required to use a specific convention, in which case, use that instead).

Using variables

After you have assigned a variable, you can reference the value that it holds simply by typing its name:

myMessage = 'Hello, world!'
print(myMessage)

Back to main page