Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Values and Variables

Your greeting worked, but you had to edit the text to change what it said. What if a program needs to remember a speed, a sensor reading, or a count? That’s where variables come in. We’ll start with a few numbers and watch what changes.

Naming and updating values

A variable is a name referring to a value. In pieces = 2, the = means assignment: evaluate the right side, then associate that result with the name on the left. This is different from an equation saying two expressions are equal.

Python values have types. An int is an integer such as 2; a float is a number such as 0.5; a str is text such as "intake"; a bool is True or False. Types affect what operations make sense. "2" is text, even though it contains a digit. We will use booleans for decisions later.

Choose names that explain a value, such as motor_request, rather than x when its meaning isn’t obvious. Python names are case-sensitive: pieces and Pieces are different names. Use lowercase words with underscores for our variables. print can receive multiple values separated by commas and display them together.

Read it before running it

Put this worked example in student-work/foundations/values_and_variables.py. Read it once and write down what you think it prints. Then save and run python student-work/foundations/values_and_variables.py using your environment’s Python.

values_and_variables.py
pieces = 2
saved_count = pieces
pieces = 3
print("Current count:", pieces)
print("Earlier count:", saved_count)

The output is Current count: 3 and Earlier count: 2. Trace the assignments:

After this linepiecessaved_count
pieces = 22not assigned
saved_count = pieces22
pieces = 332

saved_count receives the value at the time of assignment. It is not a formula that keeps watching the other name. This distinction will matter when you store a previous sensor reading. Change the first value to 5 and predict both outputs before running.

Try it yourself

Before moving on

Think about the type of each value and why a saved number does not automatically update. Recall the difference between saving this file and committing it.