6.1 Python Variables
We ended the last section (§5.3) in the Python version of the ‘hello world’ program, so let’s pick up there.
We want to develop our program to make it easier to maintain by replacing the string literal in our print statement with a variable. We are modifying our code but we have not changed any requirements (a practice called ‘refactoring’), so first run our tests to confirm the code is working.
1poetry run pytest
1============================== test session starts =============================== 2platform linux -- Python 3.9.2, pytest-7.1.2, pluggy-1.0.0 3rootdir: /home/vagrant/python 4plugins: bdd-6.0.1 5collected 1 item 6 7tests/test_convert.py . [100%] 8 9=============================== 1 passed in 0.03s ====================================================
Now edit the program.
1vi convert.py
To match the following.
1greeting_message = "Hello World!" 2print(greeting_message)
Save the changes.
In line 1 we assign the variable greeting_message the same literal string "Hello World!" we printed before. Then in line 2 we use the greeting_message variable in place of the literal string.
Re-run the tests to confirm we have broken nothing.
1poetry run pytest
1============================== test session starts =============================== 2platform linux -- Python 3.9.2, pytest-7.1.2, pluggy-1.0.0 3rootdir: /home/vagrant/python 4plugins: bdd-6.0.1 5collected 1 item 6 7tests/test_convert.py . [100%] 8 9=============================== 1 passed in 0.03s ====================================================
The program is producing the same result, so our change has broken nothing.
We now use a variable (a variable is simply a label on a piece of data) to refer to our greeting message. We will see in the following sections how to use this variable to do something more interesting.