What is a Variable?

  • A variable identifier, or variable for short, is just a name for a value. When a variable receives its value in an input statement, the variable then refers to this value.

Variable Example:

  • In reference to our Ex1_HelloWorld.py file, we can create a variable by adding a line at the beginning of the file, and modify the second line:
python
1message = "Hello Python World! Stay safe and be well"
2print(message)

Running this would provide the same output:

1Hello Python World! Stay safe and be well
  • Note that when the interpreter processes the first line, it associates the text “Hello Python World!” with the variable message. The = symbol means assignment, not equality.
  • When it reaches the second line, it prints the value associated with the message to the screen.

Avoid Name Errors When Using Variables:

  • Good coders know how to respond to errors efficiently. Let’s look at a common error and learn how to fix it. Note the misspelled word mesage shown below:
python
1message = "Hello Python World!"
2print(mesage)
  • When an error occurs in your program, the Python interpreter does its best to help you figure out where the problem is. Specifically, the interpreter provides a traceback of when a program cannot run successfully.
  • Below is an output example of the traceback after misspelling a variable’s name:
1    Traceback (most recent call last):
2      File "Act2_Strings.py", line 2, in module
3        print(mesage)
4    NameError: name 'mesage' is not defined
  • The output reports that an error occurs in line 2 of the file.
  • The interpreter shows this line to help us spot the error quickly and tells us what kind of error it found. In this case, it found a name error and reports that the variable being printed, mesage, has not been defined.
    • Note that the Python interpreter doesn’t spellcheck your code, but it does ensure that variable names are spelled consistently.