Let's take a look at the exercise that we worked on earlier, where we had to compute the cost of a meal, after tax and tip.
Assuming that we have a cost of food of $100, NY Sales Tax of 8.875% and a tip of 20%, the calculation is:
print("The cost of the meal will be:")
print(100 + 100 * 8.875 / 100 + 100 * 20 / 100)
The cost of the meal will be: 128.875
Let's say now that we want to update the cost of food to be $75. You will notice that we need to go to multiple places in the expression and modify the value that corresponds to the cost of the food.
print("The cost of the meal will be:")
print(75 + 75 * 8.875 / 100 + 75 * 20 / 100)
The cost of the meal will be: 96.65625
By using variables, we can assign a mnemonic name to each value, and use the name instead of the value itself.
Let's use variables for the cost of the food, the tax, and the tip. We can also assign the cost of the meal to another variable, calculated using the other variables.
food = 75
tax = 8.875 / 100
tip = 20 / 100
cost = food + food * tax + food * tip
print("The cost of the meal will be:")
print(cost)
The cost of the meal will be: 96.65625
In Python, a variable can be named almost anything, according to the whims of the programmer.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they cannot start with a number. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter. The underscore character (_) can appear in a name. It is often used in variables names with multiple words, such as my_name
or airspeed_of_airplace
. Variable names can also start with an underscore character, but we generally avoid doing this unless we are writing library code for others to use.
Variables are declared by stating the variable name and assigning to it using the "=" operator. At any time, you can reassign a value to a variable.
n = 17
print(n)
17
pi = 3.1415926535897931
print(pi)
3.141592653589793
message = "I love Python..."
print(message)
print(message)
print(message)
print(message)
I love Python... I love Python... I love Python... I love Python...
males = 7
females = 10
fraction = males / (males + females)
print("Percentage of men:")
print(100 * fraction)
Percentage of men: 41.17647058823529
Let's revisit our meal cost calculation code:
food = 75
tax = 8.875 / 100
tip = 20 / 100
cost = food + food * tax + food * tip
print("The cost of the meal will be:")
print(cost)
The cost of the meal will be: 96.65625
Now let's update the cost of the food:
food = 100
And let's see the cost of the meal:
print("The cost of the meal will be:")
print(cost)
The cost of the meal will be: 96.65625
You will see that the value of the cost
variable remained 96.65, and it was not automatically updated when we updated the food
variable..
To update the cost
variable, we need to execute again the calculation:
cost = food + food * tax + food * tip
print("The cost of the meal will be:")
print(cost)
The cost of the meal will be: 128.875
Notice that the value of food
persisted from the prior cell.
Let's work on another example, to practice the use of variables. We will also see an example of updating the value of a variable.
Upon taking this class, you are recruited in a new hot startup. They offer you a starting salary of $150K, a promised 25% bonus, and an equity package currently worth $400K, vesting over a period of 4 years. You want to examine the true value of this package, so you write the following program:
# A small example to start
base_salary = 150000
expected_bonus = 0.25
equity = 400000
years_vesting = 4
# Base scenario
yearly_value = base_salary + expected_bonus * base_salary + equity / years_vesting
print("The yearly value of this offer is", yearly_value)
The yearly value of this offer is 287500.0
Now, we will write the same program, but we will do the calculation in three steps. Notice that we will update the yearly_value
in steps.
# Same computation as above, but in three steps
# We start by adding the base_salary in the yearly_value
yearly_value = base_salary
# then we add the expected bonus
yearly_value = yearly_value + expected_bonus * base_salary
# and then we add the value of equity
yearly_value = yearly_value + equity / years_vesting
print("The yearly value of this offer is", yearly_value)
The yearly value of this offer is 287500.0
As expected, the outcome is the same as before.
Let's see one more variation of the same program, but now we will introduce the +=
operator. The command
x += y
means "add the value of variable y
to the variable x
".
# Same computation as above, but using the += shorthand
yearly_value = base_salary
yearly_value += expected_bonus * base_salary
yearly_value += 0 * equity / years_vesting
print("The yearly value of this offer is", yearly_value)
The yearly value of this offer is 187500.0
Now let's do the following exercise. You not only want to know the value with the current company valuation ($400K equity) but also want to see what would happen if your equity is worth nothing at the end, and also examine what would happen if the company does really well, and grows by a factor of 10x. Write the code for the two scenarios below.
# Crash and burn scenario. Equity is worth nothing at the end
# your code here
# Optimistic scenario. The company goes up a lot, and equity is worth 10x more
# your code here
Notice the importance of selecting good variable names, to make the program readable.
The program below is identical to the one above, but with less explanatory names for the variables. Instead, we have comments to document the code.
s = 150000 # salary
b = 0.25 # bonus percentage
e = 400000 # value of promised equity
y = 4 # years for vesting equity
v = s + b * s + e / y # compute the yearly value
print("The yearly value of this offer is", v)
The yearly value of this offer is 287500.0
Now, let's take the comments away. The program will run in exactly the same manner; comments are purely for humans to read, not for the computer. Still, notice how cryptic the program becomes.
s = 150000
b = 0.25
e = 400000
y = 4
v = s + b * s + e / y
print("The yearly value of this offer is", v)
The yearly value of this offer is 287500.0
And here is the same program again, but with really bad selection of variable names. (You may find it artificial, but this is an example of variable names in a real student project submitted a few years ago.)
whiskey = 150000
beer = 0.25
gin = 400000
vodka = 4
rum = whiskey + beer * whiskey + gin / vodka
print("The yearly value of this offer is", rum)
The yearly value of this offer is 287500.0
Remember, the most frequent other person that will read your code is your future self. Treat your future self nicely!
If you give a variable an illegal name, you get a syntax error:
# 76trombones is illegal because it begins with a number.
# REMOVE THE COMMENT CHARACTER IN THE NEXT LINE TO ATTEMPT
76trombones = 'big parade'
File "<ipython-input-21-8008bb527fb5>", line 3 76trombones = 'big parade' ^ SyntaxError: invalid syntax
# more@ is illegal because it contains an illegal character
more@ = 1000000
File "<ipython-input-22-b4980dc9e0ab>", line 2 more@ = 1000000 ^ SyntaxError: invalid syntax
# You cannot have spaces in variable names
daily diff = 10.10
# Using underscore is fine though
daily_diff = 10.10
# What’s wrong with class? It turns out that "class" is one of Python’s keywords.
class = 'Introduction to Programming'
File "<ipython-input-25-6afcc7da9528>", line 2 class = 'Introduction to Programming' ^ SyntaxError: invalid syntax
Python 3 has 33 reserved keywords, which are listed below and are also available in the Python manual. It a very common mistake for beginners to use some of the reserved keywords below as their variable names, so please try to be vigilant about such mistakes. The editor will help you, as reserved keywords are often colored differently.
Notice that the code below will not run because "raise
" is a reserved keyword
# Remove the comment characters to try
current_salary = 125000
raise = 35000
next_salary = current_salary + raise
File "<ipython-input-26-b260b5e515c3>", line 3 raise = 35000 ^ SyntaxError: invalid syntax
While it is prohibited to use reserved keywords, Python allows the to create variables that correspond to common functions. This can lead to very strange behaviors. In general, it is a good practice to avoid using variables that are getting colored in a different color in the editor.
print = 100
print("What happened?")
TypeErrorTraceback (most recent call last) <ipython-input-27-ce92a506a298> in <module> 1 print = 100 ----> 2 print("What happened?") TypeError: 'int' object is not callable
# Let's fix the mess...
del print
We use variables to store values.
We can use variables to make our calculations readable and easier to update.
Variable values persist between cells. Variable values keep the value from the last executed cell that updated them. (Remember that you can execute cells in any order.)
Using good variable names makes our programs easier to read and understand.
Variable names contain letters, numbers, and underscores; variable names cannot start with numbers.
There are a few reserved keywords that cannot be used. It is also a good idea not to use common function names as variables (eg., print
, min
, max
, etc.; they are all function and are colored green in the editor)