Type Coercion

Computer Science: KS3, topic 2.3.5

Type Coercion

Type coercion allows us to operate on data of different types.

Type coercion

Type coercion

  • Usually, attempting to use data of different types in an operation (e.g. adding a string to a number) will cause an error.
  • Type coercion allows one of the types to be automatically converted so that compatible operations can be completed.
Integers and floats

Integers and floats

  • When working with a float and an integer, the final result will become a float.
  • E.g: 3 + 2.5 = 5.5
Strings and integers

Strings and integers

  • When you want to combine a string and an integer, you must convert the integer to a string.
  • E.g: "Number = " + str(3)
  • Output: "Number = 3"

Test yourself on Type Coercion

  • What is the data type of a calculation involving a float and an integer?

  • What is the data type of an operation involving a string and an integer?

Practise this topic for free