19. Checking Data Types

  • It is very important to be able to check the type of data entered
  • If you try to convert data to a type that won’t ‘fit’, your program will crash
  • The code below will crash if a non-numeric input is supplied
#This will crash if you enter a string
x = input("Enter a number: ")
x = int(x)
  • The example below uses the Try/Except statement to catch the error
  • The program attempts to execute the code in the try section
  • If an error occurs, the code in the Except section is executed
  • This works equally well at checking float() conversions too
#This will catch the error, print a message, and set x = 0
x = input("Enter a number: ")

try:
   x = int(x)
except:
   x = 0
   print("You didn't enter a number")

Tasks

  • Type in the code above and ensure it works
  • Modify the program to output “You entered a number” if the input is valid
  • Save and label your code

Extension Task

You can use this technique to detect an attempt to divide by zero. Use this code to create a small program that will ask for two numbers and detect any attempt to divide by zero