Seneca

Casting

Computer Science: KS3, topic 2.3.4

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.
  • So we may need to convert a certain piece of data to a string.
  • All input also comes as a string.
  • Input 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.

Test yourself on Casting

  • Why is casting often needed for output in a program?

  • Select the statement that is true for each casting function.

Practise this topic for free