CodeSports

5.4 Data Types Make Overview

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

Instructions:


Create new code to perform the following tasks:

  • Get input for ‘length’ and ‘width’ as floats from the user
  • Multiply the length and width to get the ‘area’
  • Print the area as part of a sentence

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

num_1 = 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))

Slide Deck:


The slideshow that are part of this section can be found here:

https://docs.google.com/presentation/d/1KN5LkKUI5LiVpOnr27HTCMtdODOqScXQ8LnROVvtOwI/edit?usp=sharing

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