Data Types and Type Conversion#

Learning Objectives

Questions

  • What kinds of data do variables 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.

  • Use built-in functions to convert between integers, floating point numbers, and strings.



Data types control operations#

A value’s type determines what the program can do to it.

print(5 - 3)
Hide code cell output
2
print('hello' - 'h')
Hide code cell output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 1
----> 1 print('hello' - 'h')

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Using the + and * operators on strings#

“Adding” character strings concatenates them.

full_name = 'Ahmed' + ' ' + 'Walsh'
print(full_name)
Hide code cell output
Ahmed Walsh

Multiplying a character string by an integer N creates a new string that consists of that character string repeated N times (since multiplication is repeated addition).

There are more ways that traditional math operators will work on other data types. There is not a perfect formula for figuring out what they do, so experimentation is valuable.

separator = '=' * 10
print(separator)
Hide code cell output
==========

Here, the variable “separator” is set to the value “=” (equals sign) ten times in a row.

Strings have a length (but numbers do not)#

The built-in function len() counts the number of characters in a string.

print(len(full_name))
Hide code cell output
11
  • But numbers don’t have a length (not even zero).

print(len(52))
Hide code cell output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 print(len(52))

TypeError: object of type 'int' has no len()

Dealing with different data types#

You cannot add numbers and strings.

print(1 + 'A')
Hide code cell output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 print(1 + 'A')

TypeError: unsupported operand type(s) for +: 'int' and 'str'

This is not allowed because it is ambiguous: should 1 + '2' be 3 or '12'?

  • Some types can be converted to other types by using the type name as a function.

print(1 + int('2'))
print(str(1) + '2')
Hide code cell output
3
12

Integers and floats can be mixed freely in operations#

Integers and floating-point numbers can be mixed in arithmetic. Python automatically converts integers to floats as needed.

print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
Hide code cell output
half is 0.5
three squared is 9.0

Variables only change value when something is assigned to them#

If we make one cell in a spreadsheet depend on another, and update the latter, the former updates automatically.

This does not happen in programming languages.

first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
Hide code cell output
first is 2 and second is 5

Python reads the value of first when doing the multiplication, creates a new value, and assigns it to second.

After that, second does not remember where it came from.


Exercises#

Exercise 1: What kind of data type?#

What type of value is 3.4? How can you find out?


Exercise 2: Automatic type conversion#

What type of value is 3.25 + 4?


Exercise 3: 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 since the start of the year.

  3. Standard book loan period.

  4. Number of reference queries in a year.

  5. Average library classes taught per semester.


Exercise 4: Strings to numbers#

Where reasonable, float() will convert at string or an integer to a floating point number, and int() wil convert a string or a floating point number to an integer.

(Note, conversion is some times also called typecast.)

print("string to float:", float("3.4"))
print("float to int:", int(3.4))
Hide code cell output
string to float: 3.4
float to int: 3

If the conversion does not make sense, however, an error message will occur:

print("string to float:", float("Hello world!"))
Hide code cell output
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 1
----> 1 print("string to float:", float("Hello world!"))

ValueError: could not convert string to float: 'Hello world!'

Given the information above:

  1. What do you expect the following program to do?

  2. What does it actually do?

  3. Why do you think it does that?

print("fractional string to int:", int("3.4"))

Exercise 5: Adding floats and strings#

Given this code:

first = 1.0
second = "1"
third = "1.1"

Which of the following will print 2.0?

(There may be more than one right answer.)

  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


Exercise 6: Number of students#

If num_students is the number of students enrolled in a course (let say 600), and num_per_class is the number that can attend a single class (let say 42):

Write an expression that calculates the number of classes needed to teach everyone.

The output should look like this:

600 students, 42 per class
14 full classes, plus an extra class with only 12 students

Key points#

  • Every value has a type.

  • Use the built-in function type() to find the type of a value.

  • Types control what operations can be done on values.

  • Strings can be added and multiplied.

  • Strings have a length (but numbers do not).

  • Preventing Errors: Handling numbers and strings in Python operations.

  • Integers and floats can be mixed freely in operations.

  • Variables only change value when something is assigned to them.