Python training exercise 10
Contents
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!")
Write a small program where you ask the user for a positive whole number (a natural number). Make sure that the user gives you this kind of number, if not ask the question again. If you have the number, see if it's divisible by two and let the user know. [click on show more for answer) |
---|
def getNumberFromUser(): number = None while (number == None): userString = input("Please give a natural number: ") # Better style here would be to check the string with a regular expression, # but this will work as well try: number = int(userString) if number < 0: print(" {} is negative... try again.".format(number)) number = None except: print(" {} is not a natural number... try again.".format(userString)) number = None # Add new line for clarity of user interaction print return number if __name__ == '__main__': number = getNumberFromUser() # Check if divisible by two if not number % 2: print("{} is divisible by two!".format(number)) else: print("{} is not divisible by two!".format(number)) |