Solutions

Decimals and fractions

  1. print(type(3.4))
    <class 'float'>
  2. print(type(1/3))
    <class 'float'>
  3. print(type(4/4))
    <class 'float'>

Choose a Type

Possible answers to the questions are:

  1. Integer, since the number of days would lie between 1 and 365.
  2. Floating point, since fractional days are required
  3. Character string if serial number contains letters and numbers, otherwise integer if the serial number consists only of numerals
  4. This will vary! How do you define a specimen’s age? whole days since collection (integer)? date and time (string)? Number of seconds since creation (integer/float)
  5. Choose floating point to represent population as large aggreates (eg millions), or integer to represent population in units of individuals.
  6. Floating point number, since an average is likely to have a fractional part.

Values and types

  1. 7.25, float
  2. 7.25, float, (In Python 3 the whole calculation is treated as floating point irrespective of the order of the values)
  3. 1, int, the calculation is performed as floating point (in Python 3) and then converted to an integer
  4. ValueError: invalid literal for int() with base 10: '3.4'
    Python is unable to convert from a string to integer unless the string is an 'integer'.
  5. 3, int
    But it can convert first to a float and then to an integer.
  6. 3, int
    When converting to an integer Python does not 'round the value to the nearest integer but effectively ignores the fractional/decimal part
  7. ValueError: could not convert string to float: 'Hello World!'

Calculating with variables with different types

1 and 4 give the result 2.0. The complete results should be:

  1. 2.0
  2. 2.1
  3. ValueError: invalid literal for int() with base 10: '1.1'
  4. 2.0
  5. 2
  6. TypeError: can't multiply sequence by non-int of type 'float'