Datatypes and Conversion

Overview:

  • Teaching: 10 min
  • Exercises: 5 min

Questions

  • Why are there different types of values a computer can store?
  • What kind data types do programs store?
  • How can I convert one type to another?

Objectives

  • Explain key differences between integers and floating point numbers.
  • Explain key differences between numbers and character strings.
  • Understand how to assign a value so it has the correct type.
  • Use built-in functions to convert between integers, floating point numbers, and strings.

Every value has a type

So far we have introduced different types of values. Before we go any further we will explore this a little more to ensure that we are clear about differences between the types of values and the variables where they are stored.

  • Every value in a program has a specific type.
  • Integer (int): represents positive or negative whole numbers like 3 or -512.
  • Floating point number (float): represents real numbers like 3.14159 or -2.5.
  • Character string, usually called a string, (str): "some text".
    • Written in either single quotes or double quotes (as long as they match).
    • The quote marks aren’t printed when the string is displayed with print().

The type function

We will use the function type to identify how Python stores the following values.

In [1]:
print(type(24))
<class 'int'>

24 is recognised as a value of type 'int', where 'int' as we might expect is short for integer.

In [2]:
print(type(70.0))
<class 'float'>

70.0 is a 'float'. Finally:

In [3]:
print(type("James"))
<class 'str'>

What about variables?

Hopefully there are no surprises in the types that Python assigns to the values above, but what about variables. Let's try run type on a new variable, changeling:

In [4]:
print(type(changeling))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-e94e480168f6> in <module>
----> 1 print(type(changeling))

NameError: name 'changeling' is not defined

As we found out at the end of the last episode, we cannot use a variable before it has been assigned a value. So let's assign a series of values and repeat:

In [1]:
changeling = 24
print(type(changeling))
<class 'int'>
In [2]:
changeling = 70.0
print(type(changeling))
<class 'float'>
In [3]:
changeling = "James"
print(type(changeling))
<class 'str'>

We can see that in Python variables do not have a well defined type but are mutable, depending upon the value stored in them

Value types determine what operations are allowed

The type of values determines what can be done with them for instance we have already seen that we can happily perform calculations e.g.:

In [4]:
print(5-3)
2

We have also seen that if we mix integers and floats, Python is able to work out what to do:

In [5]:
print(2+3.5)
5.5

Because integers and floats are ways of representing numbers mathematical operations involving their values are well defined.

What about the following?

Think about what would happen if you tried the following and then see if you can understand the output.

  1. print(1+"2")
  2. print("Hello"-"world")

Now try these:

  1. print("Hello"+"world")
  2. print("Hello"*3)

Choosing the type of value.

In the previous episode we used

age = 36
name = "James"
print(name, "is", age, "years old")

What would happen if we had instead used

age = "36"
name = "James"
print(name, "is", age, "years old")

Think about why we would choose to specify age as an integer (or float) rather than a string.

Changing the type of a value

As well as using the function type to retrieve the type of a value there are also a set of functions which can be used to change the type of a value. These functions take the form of the value types int(), float() and str()

In [6]:
print("String:","2", "Integer:", int("2"), "Float:", float("2")) # Take the string "2", convert it to a integer, a float and print all three cases
String: 2 Integer: 2 Float: 2.0
In [7]:
print("Float", 2.5, "String:", str(2.5), "Integer:", int(2.5))   # Take the float 2.5, convert it to a string, an integer and print all three cases
Float 2.5 String: 2.5 Integer: 2

In [8]:
print(1 + int("2")) 
3

Alternatively it may have been our intentions to 'add' or combine the two strings "1" and "2" in which case we would instead need:

In [10]:
print(str(1)+"2")
12

What about a variables type?

So far we have used the functions str, int and float, to change the type of values. How does running these commands on a variable affect the type of the value assigned to them? When can investigate this with the following:

In [11]:
my_variable = "2"               # First we assign the value, string "2", to the variable my_variable
print(my_variable)              # Print the variable
print(my_variable*5)            # Verify that the variable is a string but testing the behaviour with `*`
print( float(my_variable) )     # Convert the value in variable to a float and print it
print(my_variable*5)            # Verify what the variable type is now by testing the behaviour with `*`
2
22222
2.0
22222

We see that this has not changed the type of the value stored in my_variable. The commands only change the type of the value at that point in the code. For example if we have the string "2", running int("2") does not change the fact that "2" is a string.

If we want the conversion to be reflected in the value stored in a variable, we must reassign the variable:

In [12]:
my_variable = "2"                   # First we assign the value, string "2", to the variable my_variable
print(my_variable)                  # Print the variable
print(my_variable*5)                # Verify that the variable is a string but testing the behaviour with `*`
print( float(my_variable) )         # Convert the value in variable to a float and print it
my_variable = float(my_variable)    # Now we explicitly reassign the my_variable
print(my_variable*5)                # Verify what the variable type is now by testing the behaviour with `*`
2
22222
2.0
10.0

We can now see that the variable has been explicitly reassigned to the value converted to a float, and this has been verified by checking that * now performs the numerical operation we expect rather than the repeating the string multiple times.

Decimals and fractions

What type of values are the following and how can you find out?

  1. 3.4
  2. 1/3
  3. 4/4

Solution

Choose a Type

What type of value (integer, floating point number, or character string) would you use to represent each of the following? Try to come up with more than one good answer for each problem. For example, in # 1, when would counting days with a floating point variable make more sense than using an integer?

  1. Number of days since the start of the year.
  2. Time elapsed from the start of the year until now in days.
  3. Serial number of a piece of lab equipment.
  4. A lab specimen’s age
  5. Current population of a city.
  6. Average population of a city over time.

Solution

Values and types

What will be the value and type resulting from the following. Trying working them out first then try the for yourself.

  1. 3.25 + 4
  2. 4 + 3.25
  3. int(4/3)
  4. int("3.4")
  5. int(float("3.4"))
  6. int(3.99)
  7. float("Hello world!")

Solution

Calculating with variables with different types

Which of the following will print 2.0? Note: there may be more than one right answer.

first = 1.0
second = "1"
third = "1.1"
  1. first + float(second)
  2. float(second) + float(third)
  3. first + int(third)
  4. first + int(float(third))
  5. int(first) + int(float(third))
  6. 2.0 * second

Solution

Division Types

In Python 3, we have seen how the / operator performs floating-point division, even if the values that it operates on are integers, these are first converted to floats. If we want to explicitly tell Python 3 to perform an integer calculation, the // operator performs integer (whole-number) floor division, and the % (or modulo) operator calculates and returns the remainder from integer division. Try the following:

print('5 // 3:', 5//3)
print('5 / 3:', 5/3)
print('5 % 3:', 5%3)

Once again try to work out what the result, and its type are likely to be before running the code.

Key Points:

  • Every value has a type.
  • In Python you can use the built-in function type to find the type of a value.
  • The type controls what operations can be done on values.
  • Strings can be added and multiplied.
  • Must convert numbers to strings or vice versa when operating on them.
  • In Python you can mix integers and floats freely in operations.
  • Variables only change value when something is assigned to them.