CodeSports

5.2 Data Types Investigate Overview

Students will learn more about the types of data within Python code.

Instructions:


Examine the example code and answer the questions below. Make sure to comment (#) while typing your answers

Learning Goals:


Be able to read, comprehend, trace, adapt and create Python code using selection that:

  • Uses different data types
  • Uses casting

Data Types:


A data type is a setting for a variable that tells it what sort of data to accept. The three data types we will use in these exercises are:

  • String – Text. All data in string variables are treated as text
  • Integer (Int) – Whole Numbers
  • Float – Decimal Numbers

Casting:


Casting is the act of converting variables to different data types. This can be done with separate functions:

  • int(variable) converts the variable within into a whole number, if it is a number
  • float(variable) converts the variable within into a decimal number, if it is a number
  • str(variable) converts the variable within into a text-based string

Casting is also used during input. Normally, all inputs from the user are strings, but it can be casted into a different data type and stored into a variable: Example

num1 = int(input(“Enter a number -> “))

Operators:


Certain operators are used to compare data types, they are:

  • Equal to ==
  • Not equal to !=
  • Greater than x>y
  • Less than x<y
  • Mathematical operations (+ – * /)

Note that string data types cannot be used with mathematical operations

Type Function:


The type function returns the data type of a variable or piece of data. Examples include:

  • type(6) returns integer
  • type(5.6) returns float
  • type(“Hello World!”) returns string

The data type can be printed as well.

print(type(6))

Help! My Code Does Not Work!


When you encounter errors you can code, make sure to check if:

  • str() casts to string
  • int() cast to whole numbers
  • float() cast to decimal numbers
  • The variable is inside the bracket after the casting’
  • The cast data has been assigned to a variable

Hints