Skip to content

Variables#

In our Bash script we used variables to store values. Python (and every other programming language) is no different - you use variables to store values using a name you can refence later on.

In Python creating a variable and assigning it a value is simple. In our main() function we do this:

1
2
3
def main():
  name = ""
  repeat = "no"

Variables must be defined in advance. That means you must create/define the variable before you can use it.

The variable's name should provide some indication as to what the value assigned to it is. What's its purpose?

Programmers often use short variable names, such as x, j, etc. In most cases, you should avoid single-character names and use something more descriptive so that other developers can make an educated guess as to the value the variable holds.

Here are some examples of valid and invalid variable names in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> numbers = [1, 2, 3] # valid
>>> numbers
[1, 2, 3]

>>> one_good_number = 1 #valid
>>> one_good_number
1

>>> 1bad_number = 1 # invalid, hence error
  File "<input>", line 1
    1bad_number = 1
    ^
SyntaxError: invalid syntax

>>> π = 3.1415 # Using unicode characters is fine in Python 3
>>> π
3.1415

Variable names can be any length, but you should keep them concise. They can be made of uppercase and lowercase letters, numbers, and the underscore character. The first character in a variable cannot be a digit (see examples above.)

And yes, the little π (Pi) icon is legal! Python 3 support unicode, so you can even use emojis in strings (but not to start a variable name):

1
2
>>> print("👍")
👍