How it Works: ValueError

This type of application is explained in detail in Computer - micro:bit Talk, leading up to the apps in the Input/Print for Applications page.  So, let’s just look at the exceptions that occurred.  

Like the previous activity, when you typed 0 and pressed enter, a ZeroDivisionError exception occurred at the q = n / d statement since it cannot give you an answer with d = 0.  No surprise here.

Next, when you tried “Hello" in the denominator,  a new error occurred—the ValueError. This is different from TypeError we saw previously. In our earlier example that used the terminal, d was defined as an int. Here, d is defined as a float.

So, here the code froze when it tried to execute float(“Hello”).  The float function can convert text that represents a value into that value.  So, in d = float("5"), the float function receives the text string “5” and returns the value 5.  That value gets stored in the variable d.

If a variable named text stores the string “5”, then d = float(text) will also store the value 5 in d.  In contrast, d = float(“Hello!”) has non-digits that the float function cannot convert to a number.  At that point, the MicroPython runtime raises the ValueError exception.


Did You Know?

While developing the app, it’s still a good idea to to display the error and type so that you can attempt to “break” the code with different variations of user input errors.

Your script can selectively address more than one kind of exception with a single action.  For example, if you want it to display the “Expected a number.” message for either a TypeError or a ValueError, you could use this:

    except (TypeError, ValueError):                  
        print("Expected a number.")