- At many points in a program, we need to "hold on" to a value so that we can do something else with it.
>>> print("Agent's current position", (3 + 8 * 2), (3 + 8 * 1))
Agent's current position 19 11
>>> print("Agent's distance from right wall", 50 - (3 + 8 * 2))
Agent's distance from right wall 31
>>> print("Agent's distance from bottom wall", 50 - (3 + 8 * 1))
Agent's distance from bottom wall 39
- A variable is a symbol that is a placeholder for a value.
- To create a variable and give it a value, we use an assignment statement.
-
An assignment statement consists of the variable name, followed by the
= operator, followed by an expression that evaluates to the value we are giving the variable.
Note that an assignment statement is not a function, so it does not have arguments within parentheses.
>>> agent_x = 3 + 8 * 2
>>> agent_y = 3 + 8 * 1
>>> print("Agent's current position", agent_x, agent_y)
Agent's current position 19 11
>>> print("Agent's distance from right wall", 50 - agent_x)
Agent's distance from right wall 31
>>> print("Agent's distance from bottom wall", 50 - agent_y)
Agent's distance from bottom wall 39
- We also use an assignment statement to update the value of a variable that already exists.
>>> agent_x = 19 + 5 * 2
- The variable being reassigned can also appear on the right side of the assignment operator.
>>> agent_y = agent_y + 5 * 1
>>> print("Agent's new position", agent_x, agent_y)
Agent's new position 29 16
- There are some constraints on what can be a variable name.
>>> position1 = 3
>>> 1position = 3
SyntaxError: invalid syntax
>>> agent position = 3
SyntaxError: invalid syntax
>>> agent-position = 3
SyntaxError: can't assign to operator
>>> agent_position = 3
>>> print = 'print'
SyntaxError: invalid syntax
- In Python, you can assign multiple variables in the same statement.
The names and values are separated by commas.
>>> agent_x, agent_y = agent_x + 2, agent_y + 1
>>> print("Agent's new position", agent_x, agent_y)
Agent's new position 31 17