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:

Checks For Understanding

Q#1

    ch0104-1: What datatype will result from the following expression? 4 * 2.0
  • (A) Boolean
  • Remember that a boolean is True/False, which isn't in this expression.
  • (B) Integer
  • Which is greater, Floats or Integers?
  • (C) Float
  • The float turns everything into a float!

Q#2

Evaluate the following expression: 8 / 2 ** 2.0. Don’t forget to consider order of operations as well as the datatypes. Have you considered the ending datatype? Don't forget about order of operations! Don't forget about order of operations! Try again!

Q#3

Evaluate the following expression: 10 / 4 + 4.0. Don’t forget to consider order of operations as well as the datatypes. Have you considered the ending datatype? Don't forget about order of operations! Try again!

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.

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?

Next Section - Lesson 01-05: Conversion Functions