Lesson 01-04: Mixing Datatypes¶
Learning Target: I can predict the behavior of two different datatypes that are operated upon.
Now that we know that we can use operators to combine values, what happens if we combine values of different types?
Mixing Ints with Floats¶
When you mix integers and floats together, you will always get a float back. Integer and integer gives integer, float and float gives float, but combining an integer and float will result in a float.
To observe, run the following code:
print(1 + 1) #int + int => int
print(1.0 + 1.0) #float + float => float
print(1 + 1.0) #int + float => float
Note that everything after the # is a comment and is not run as code (ac_mixtype_1)
Checks For Understanding¶
Q#1¶
4 * 2.0
Q#2¶
8 / 2 ** 2.0
. Don’t forget to consider order of operations as well as the datatypes.
Q#3¶
10 / 4 + 4.0
. Don’t forget to consider order of operations as well as the datatypes.
Mixing Strings with Anything¶
We already know that we can multiply Strings with integers. This seems to be the exception, because in every other case, we’ll get an error! Let’s look at string addition (recall: concatenation).
In the following code, replace the 1
with any other value that is not a String, then run the code. You should find a common theme.
print("hello" + 1)
#replace the second part with anything that is not a String
(ac_mixtype_2)
You should find that you get a TypeError
every time!
- The rule can basically be broken down into three parts:
- Adding a string to another string is allowed
- Multiplying a string by an integer is allowed
- Everything else is not allowed
Any time we encounter code that generates an error, it’s usually a good idea to find a way to make the code work without any errors. So the big overarching question in our next lesson is: How do we combine different types?