Data Types

Coding: Introduction to Python v3, topic 1.3.1

Data Types

Every piece of data that is stored has a type. The type determines how it is stored and what you can do with the data.

Integer

Integer

  • Integers are whole numbers.
  • E.g. 12
  • E.g. 0
  • E.g. -142
Float

Float

  • Floats are fractional numbers.
  • E.g. 0.42
  • E.g. 1.00
String

String

  • Strings are text data.
  • E.g. "Hello, world!"
  • E.g. "07123 456 789"
Boolean

Boolean

  • A True or False value.
  • Examples:
  • True.
  • False.

Casting

Casting is the process of converting data from one type to another.

Reasons for casting

Reasons for casting

  • One of the most common reasons for casting is output.
  • Output must be formatted as a string, and so we may need to convert a certain piece of data to a string.
  • All input also comes as a string, and must then be converted to other data types.
Casting functions

Casting functions

  • Casting to a string can be done using the str function. E.g:
  • str(3) gives "3".
  • Casting to an integer can be done using the int function. E.g:
  • int(3.4) gives 3.
  • Casting to a float can be done using the float function. E.g:
  • float("3.4") gives 3.4.

Type Coercion

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

Type coercion

Type coercion

  • Usually, attempting to use incompatible data 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

  • Python does not automatically coerce integers to strings when using +.
  • "Number = " + 3
  • TypeError: can only concatenate str (not "int") to str
  • To join a string and a number, you must explicitly convert the number using str().
  • "Number = " + str(3)
  • Output: "Number = 3"

Test yourself on Data Types

  • What would be the most suitable type to store the number 2.5?

  • Which of these data are strings?

  • Which would be the most appropriate type to store a username?

  • What is one of the most common reasons for casting?

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

Practise this topic for free