import sandbox_widget14 Variables
This section is about variables and is where the fun begins.
A variable is a way of assigning a name to a value. 8700000 is just a value, but if we assign a name to it, then it gets a special meaning:
%%sandbox
number_of_species = 8700000
print(number_of_species)In this case, the variable number_of_species represents the estimated number of eukaryotic species on the planet, which is 8700000. So 8700000 is the value, and “number_of_species” is the variable name. Read the code above and run it. Notice how this lets us refer to the value using the variable name. What appears in the terminal when you do that? Do you see number_of_species or 8700000?
As you can see in the small program above, one of two different things happens when a variable name appears in Python code:
- Assignment: When a variable name appears to the left of an equal sign, a value is assigned to the variable. This happens in the first line where
number_of_speciesis assigned the value8700000. - Substitution: In all other contexts, the variable is substituted for its value. This happens in the second line where Python substitutes the variable name
number_of_speciesfor its value8700000and then prints that.
That is it, but let us take the example further and create another variable to which we assign the value 1200000. That is the number of species discovered so far. Now, let us add this to the program and use it to compute the number of species we have yet to identify. Start by reading the code below super carefully. Remember that a variable is either assigned a value or substituted for the value it represents. For each occurrence of the variables below, determine if they are being assigned a value or if they are substituted for their value.
%%sandbox
number_of_species = 8700000
number_discovered = 1200000
number_unidentified = number_of_species - number_discovered
print(number_unidentified)Take some time to let it sink in that variables are extremely useful for two reasons:
- Variables give meaning to a value. Without the variable name, the value of 1200000 could just as well be the number of people that live in Copenhagen. However, by giving the value a meaningful name, it becomes clear what it represents.
- We can assign new values to variables (that is why they are called variables). For example, we can change the value of
number_discoveredas new species are discovered.
Your variable names can be pretty much anything, but they have to start with a letter or an underscore (_), and the rest of the name has to be either letters, numbers, or underscores. To be clear, a space is not any of those things, so do not use spaces in variable names. Above all, be careful in your choice of variable names. Variable names are case-sensitive, meaning that count and Count are different variables. Stick to lowercase variable names. That makes your code easier to read.
Exercise 14-1
For each occurrence of the variables below, determine if they are being assigned a value or if they are substituted for their value.
breeding_birds = 4
print(breeding_birds)
breeding_birds = 5
print(breeding_birds)Exercise 14-2
For each occurrence of the variables below, determine if they are being assigned a value or if they are substituted for their value.
breeding_birds = 4
print(breeding_birds)
breeding_birds = breeding_birds + 1
print(breeding_birds)Exercise 14-3
What happens if you run the code below, then swap the two lines and run it again?
%%sandbox
number_of_species = 8700000
print(number_of_species)Explain to yourself what happens before and after you swap them? What kind of error do you get with version two, and why?
Exercise 14-4
If you run the code below you should get an error.
%%sandbox
income = 45000
lax_percentage = 0.43
tax_amount = tax_percentage * income
income_after_tax = income - tax_amount
print('Income after tax is', income_after_tax)It says that the error is on line 3. Can you figure out what is wrong? Hopefully, you will now appreciate how much attention to detail is required when programming. Every tiny, little symbol or character in your code is essential.
Different types of values
By now, you probably have a pretty good idea of what a value in Python is. So far, you have seen text like 'Banana', integers like 7, and numbers with a fractional part like 4.25.
In Python, a text value is a type of value called a string, which Python denotes as str (abbreviation for “string”). So 'Banana' is a string, and so is 'Banana split'. There are two types of numbers in Python. Integers (7, 42, and 3) are called int. Numbers with a fractional part (like 3.1254 and 4.0) are that are called float (an abbreviation for “floating-point number”).
As I mentioned earlier, True and False are Python values too. They are called booleans or bool, named after an English mathematician called George Boole famous for his work on logic.
So the different types of values we know so far are:
| Name | Type in Python | Examples |
|---|---|---|
| String | str |
"hello", '9' |
| Integer | int |
0, 2721, 9 |
| Floating-point | float |
1.0, 4.4322 |
| Boolean | bool |
True, False |
| None | NoneType |
None |
In case you did not notice, I added a special type at the end that can only have the value None. I may sound a little weird, but in programming, we sometimes need a value representing nothing or None. For now, just make a mental note that None is also a Python value.
When you do computations in Python, it is no problem to mix integers and floating-point numbers. Try this:
%%sandbox
print("What is 0.5 * 2?", 0.5 * 2)
print("What is 3 / 2?", 3 / 2)As you can see we can also make computations using only integers that result in floating-point numbers.
Some of the math operators not only work on numbers, but they also work on strings. That way, you can add two strings together. It is no longer math, of course - but quite handy.
%%sandbox
fruit = 'Ba' + 'na' + 'na'
print(fruit)Exercise 14-5
If you try to combine different types of values in ways that are not allowed in Python, you will get an error. Try each of the following weird calculations, and read each error message carefully.
%%sandbox
x = 3 - '1.5'
print(x)%%sandbox
x = None - 4
print(x)For each one, paste the error into the assistant and ask which of the two values Python is unhappy about, and why. Then decide whether you agree before you move on. These messages name types, so the assistant’s answer is easy to check: if it says Python objected to the string, the message should be saying so too.
Exercise 14-6
Write these two examples and compare the resulting values of x
%%sandbox
x = '9' + '4'
print(x)x = 9 + 4
print(x)Exercise 14-7
Try these two examples. What happens in each case? Does it make sense?
%%sandbox
x = '72' * '3'Exercise 14-8
Will this work? Use what you have learned from the other exercises and try to predict what will happen here. Then, read the code and try it out.
%%sandbox
x = 'Ba' + 'na' * 2
print(x)Exercise 14-9
Sometimes, you may need to change a string to a number. You can do that like this:
some_value = "42"
other_value = int(some_value)Write some code that converts strings to numbers and numbers to strings. Remember that numeric values are either integers or float. Use int, float as in the example above. You will notice that only meaningful conversions work. E.g., this will not work: number = int('four'). To convert a number to a string, you can use str.
Having completed the above exercises, you should take note of the following four important points:
- All Python values have a type. You know about strings, integers, floating-points, and booleans so far.
- Math operators let you do cool things like concatenating two strings by adding them together.
- The flip side of that cool coin is that Python will assume you know what you are doing if you add two strings (
'4' + '4'is'44'not8) or multiply a string with an integer ('4' * 4is'4444'not16). - You can change the type of a value, e.g.,
'4'to4or1to1.0. - Python will throw a
TypeErrorif you try to combine types values of values in ways that are not allowed.
Escape characters: An escape character is a backslash
\followed by a single character.\nand\tare the most commonly used ones.
Exercise 14-10
What do you think is printed here?
%%sandbox
main_course = 'Duck a la Banana\n'
dessert = 'Banana split\n'
menu = main_course + dessert
print(menu)Can you figure out what the special character \n represents?
Exercise 14-11
What do you think is printed here? Decide before you run the code.
%%sandbox
dish_one = 'Banana\t\tsplit'
dish_two = 'Chocolate\tcake'
print(dish_one)
print(dish_two)Can you figure out what the special character \t represents?
Mixed exercises
Each chapter in the book ends with a set of mixed exercises meant to allow you to combine what you have learned so far. In this case, they are meant to train your familiarity with the following topics:
- Strings
- Math
- Logic
- Types of values
- Variables
Exercise 14-12
What happens if you try to run the following program?
%%sandbox
print("What happens now?", 1 / )If you get an error, why do you think you get that error?
%%sandbox
print("What happens now?", 1 / 3If you get an error, why do you think you get that error? Can you fix it? (Hint: EOF is short for End Of File)
Exercise 14-13
Determine, for each of the eight occurrences of the variable x below, where it is being assigned a value and when it is substituted for its value:
%%sandbox
x = 1
x = x + 1
x = x + 1
x = x + 1
print(x)Then, figure out what is printed and why. What value does x represent at each occurrence in the code?
Exercise 14-14
Some comparison operators also work with strings. Consider this code:
%%sandbox
print("apples" == "pears")What is printed here? Decide before you run the code. If you were wrong, make sure you understand why.
Exercise 14-15
What is printed here? Decide before you run the code.
%%sandbox
print('aaaaaa' < 'b')
print('a' < 'b')
print('aa' < 'ab')
print('99' > '100')
print('four bananas' > 'one banana')By what rule does Python decide if one string is smaller than another? You may have a clue if you have looked something up in an encyclopedia recently. Also, try to google “ASCII table”.
Exercise 14-16
What is printed here? Decide before you run the code.
%%sandbox
print('banana' < 'Banana')Exercise 14-17
Do you think it is allowed to use relational operators on values of different types? Try these out and see for yourself:
%%sandbox
print('Banana' > 4)%%sandbox
print('42' == 43) # this one is dangerous...%%sandbox
print(4 in '1234')Practice reading this kind of error (TypeError).
Exercise 14-18
Can you use the in operator to test if this mini gene is part of the DNA string?
%%sandbox
mini_gene = 'ATGTAG'
dna_string = 'GCTATGTAGGTA'
print( )Exercise 14-19
Say you have two strings "4" and "2". What happens if you add them like this: "4" + "2". Can you convert each one to integers so you get 6 when you add them? (have a look at Section 14.0.0.9 if you do not remember).
Exercise 14-20
What happens if you run this code? Do you get an error? Do you remember why?
%%sandbox
1value = 42Exercise 14-21
What happens if you run this code?
%%sandbox
print('Hi')
print('Hi')
print('Hi')Compare this to what happens when you run this code:
%%sandbox
print('Hi\nHi\nHi')Do you remember what \n represents? What does it tell about what is added at the end every time you print something?
Exercise 14-22
Make three exercises for your fellow students. See if you can make them so they test the understanding of (almost) all you have learned so far.