Variables and assignment
What you need to know about variables
- A variable is a name you give to data, so you can use it later in the program
- You assign a value to a variable with
=
- There are lots names you can use for variables, but there are some rules
- Using meaningful variable names makes your program better
Video: What are variables?
Assignment Operators
We learned about the =
operator which is also called the assignment operator. It assigns the value on the right to the variable on the left.
There are other assignment operators in Python, which are shortcuts for doing math and assigning the result to a variable.
For example, the +=
operator adds the value on the right to the variable on the left, and assigns the result to the variable on the left.
x = 10
x += 5 # x is now 15
There are other similar assignment operators, like -=
, *=
, /=
, and %=
that works the same way.
Variable Names
Good and Bad Variable Names
Variable names should be descriptive and help a reader understand the code.
For example, take a look at the code below:
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd) # 437.5
The variable names above are allowed in Python, but they are not helpful.
Contrast with:
hours = 35.0
pay_rate = 12.50
pay = hours * pay_rate
print(pay) # 437.5
These variable names are descriptive and helpful!
Practice: Assigning and printing variables
Solution (try for 5 minutes before looking!)
books_read = 13
print(books_read)
meals_eaten = 4
meals_eaten = meals_eaten + 1
# you can use the += operator to do the same thing:
# meals_eaten += 1
print(meals_eaten)