Variables
Variables
- a variable is a name that refers to a value:
- once a variable is declared and assigned a value, you can use that variable where you would use any other values →
- my_variable + "!"
- print(my_variable)
- (a + b) / c
Assignment
- use the assignment operator: =
- a single equals sign
- note - does not test for equality, performs assignment!
- variable name goes on the left
- value goes on the right
Using Variables
When do you use variables?
- when you want your program to remember a value
- if you have a value that will vary
- some examples include:
- a player's score
- a count of repetitions
- user input
- sensor input
- additionally, using variables will help make your code more maintainable / less brittle
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"
- assume everything will vary / change
- avoid using a bare literal
- you remember what that is, right?
- "a string", 58.3
- sometimes this is called hardcoding
- cleaning this stuff up helps code reuse / DRY
- not having to write the same thing multiple times
- don't repeat yourself
- we saw that in the previous slide
Multiple Assignment
You can also assign multiple values to multiple variable names simultaneously. →
This is done by:
- using the assignment operator: =
- a comma separated group of variables on the left-hand side
- a comma separated group of values on the right hand side
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? →
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!) →
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
- in Python, if something is idiomatic, it's called Pythonic
- someone that codes in Python is sometimes called a Pythonista
- (yes, really)