Today I figured out a new way to use Try Except Else statements to limit input types to code

Background

Try Except Else statements consist of 3 parts. try: is a test case, except: is what to do if the test case throws an error, else: is what to do if there is no error. The case below shows the difference between an error case and how a Try Except Else statement deals with it. You can even specify the output by error if you want

Screen Shot 2022-03-07 at 6.49.25 PM.png

The Problem

I needed my program to only accept lists at the start, or many errors would occur later on. To only accept lists, I needed some code that would always cause an error if the input was not a list. This line of code would go in the “try” part of the statement. Codes like len(input) or input[0] would still work for strings so this would not fit my needs. The best way to determine type was using the type(input) but that would only give me the type, not result in an error

The Solution

If I used list=type(input) I would get True when the input was a list and False when it wasn’t. This is still not an error. I then remembered that True=1 and False=0. That means 1/True would be fine while 1/False would cause a Zero Division Error.

try:
		1/(list==type(input_variable))
except ZeroDivisionError:
		print ("Please input a list")
else:
		what_i_want_the_code_to_do

This works for any type such as strings or floats, just replace “list” with your type of choice. This solution is very short and simple but also very powerful and effective.