Variables

Variables

Assignment

Using Variables

When do you use variables?

Here's an Example of Improving Maintainability

Let's say you have a program that adds x number of exclamation points to some words. →

print("foo" + "!" * 5)
print("bar" + "!" * 5)

OR…

my_exclamation_constant = 5
print("foo" + "!" * my_exclamation_constant)
print("bar" + "!" * my_exclamation_constant)

"Hardcoding"

Multiple Assignment

You can also assign multiple values to multiple variable names simultaneously. →

This is done by:

a, b, c = 3, 21, 7

Each variable/value is bound in the order that they appear.

Multiple Assignment Continued

a, b, c = 3, 21, 7

What values are referred to by a, b, and c? →

a -> 3
b -> 21
c -> 7

Here's a Quick Exercise on a Tiny Algorithm

If I have two variables, a and b, and they are set to 3 and 21 respectively, how would I swap their values in code? (Try this on your own!) →

a = 3
b = 21
print("a:", a, "b:", b)
c = b
b = a
a = c
print("a:", a, "b:", b)

See the Python Tutor version

An Idiomatic Way to Do It

Here's another, more idiomatic way to do it

a = 3
b = 21
a, b = b, a

…And, Some BTWs

Greeaaat. Maybe we can use them to help us create our own functions!