Variables
A variable is a name refers to a value (a.k.a. a name-value pair). In Python, to make a variable name, we can use any sequence of letters and numbers and underscores, so long as it does not start with a number. Here are some examples of valid variable names:
processor_speed
n
hours
item
To introduce a new variable, we use an assignment statement:
Name = Expression
After executing an assignment expression, the name refers to the value of the expression on the right side of the assignment:
speed_of_light = 299792458
We can use the variable name anywhere we want and it means the same things as the value it refers to. Here is an expression using the name to print out the speed of light in centimeters:
print(speed_of_light * 100)
Quiz 1.4
Write Python code to print out how far light travels in a year.
We can make a variable that contains the numbers of seconds in a year:
secs_in_year = 365 * 24 * 60 * 60
Answer
speed_of_light= 299792458
secs_in_year = 365 * 24 * 60 * 60
print(speed_of_light * secs_in_year)
Variables Can Vary
The value a variable refers to can change. When a variable name is used, it always refers to the last value assigned to that variable.
shoe_price = 3000 #before sales period starts
shoe_price = 2000 #after sales period starts
This gets more interesting when we use the same variable on both sides of an assignment. The right side is evaluated first, using the current value of the variable. Then the assignment is done using that value. In the following expressions, the value of days changes from 49 to 48 and then to 47 as the expression changes:
days = 7 * 7 # after the assignment, days refers to 49
days = 48 # after the assignment, days refers to 48
days = days - 1 # after the assignment, days refers to 47
days = days - 1 # after the assignment, days refers to 46
It is important to remember that although we use =
for assignment it does not mean equality. You should think of the =
sign in Python as an arrow, <--
, showing that the value the right side evaluates to is being assigned to the variable name on the left side.
Quiz 1.5
What is the value of hours after running this code:
hours = 9
hours = hours + 1
hours = hours * 2
- A)
9
- B)
10
- C)
18
- D)
20
- E)
22
- F) Error
Answer
- D)
20
Defining Variables
For Python to be able to output a result, we need to always define a variable by assigning a value to it before using it.
minutes = 30
minutes = minutes + 1
seconds = minutes * 60
print(seconds)
Output:
1860
Quiz 1.6
Write Python code that defines the variable age to be your age in years, and then prints out the number of days you have been alive. If you don't want to use your real age, feel free to use your age in spirit instead.
Answer
age = 26
days_per_year = 365
days_alive = age * days_per_year
print(days_alive)
Output:
9490