Python training exercise 10

From BITS wiki
Jump to: navigation, search

Introduction

Your programs can and will crash. This can be because of logical errors in the code (which can be fixd), or because an unexpected value creeps into a variable from misguided user input or a file that has strange values in it (this you cannot fix).

For the last category of problems, it is useful to doublecheck variables that you cannot fully control - sometimes you want to just warn the user that something strange is happening, sometimes you want to stop the code because you can't continue with this information. What is best depends on how user-friendly you want the program to be, and how much effort you can spare - it takes a lot of time to do this correctly.

One very useful command to check values is assert, another that you can use to avoid running into errors is the try: except: combination, which we'll introduce here.

Exercises

Checking variables with assert

The assert command will raise an error if its condition is not satisfied:

myValue = 32
myDivider = 0
 
assert myDivider != 0, "Cannot divide by zero! Aborting code..."
 
print("Division is {:.2f}".format(myValue * 1.0 / myDivider))

The more user-friendly (but more verbose way) would be something like this:

myValue = 32
myDivider = 0
 
if myDivider == 0:
  print("Warning: cannot divide by zero!")
  myResult = None
else:
  myResult = myValue * 1.0 / myDivider
  print ("Division is {:.2f}".format(myResult))
 
# But can your program now continue if myResult is None?


Avoiding errors with try: except:

Another thing you can use is the try: except: combination. Python will try to execute everything in the try: block, and if that doesn't work (there's an error) it will do whatever is in the except: block:

myValue = 32
myDivider = 0
 
try:
  print(myValue * 1.0 / myDivider)
except:
  print("Cannot divide by zero!")

Back to main page