Exception Handling
Examples of exception handling and assertions
Unsolved practice questions:
Q1: Create an interactive calculator! User input is assumed to be a formula that consists of a number, an operator (arithmetic), and another number, separated by white space (e.g. 2 + 3). If the second input is not an operator, raise a TypeError. Try to convert the first and third input to a float and handle any exception it may cause. If the input is valid, perform the calculation and print out the result. The user is then prompted to provide new input, and so on, until the user enters quit.
Q2: Write a function capitalize_last_name() that accepts as argument a string with a (single) first and a (single) last name, and returns a string in which only the first letter of the first name is uppercase, whereas all letters of the last name are uppercase. For example, ‘john doe’ becomes ‘John DOE'. If something other than a str object is passed as an argument, the function should raise a TypeError. (Tip: you can use isistance() to check whether an object is of a particular type.) If the str does not consist of exactly two words, the function should raise a ValueError.
Q3: Implement a function that takes a list of numbers and an index as input and returns the square root of the element at that index. If the number is negative, the function should raise a TypeError. Call the function and handle all possible exceptions gracefully.
Q4:Develop a function that prompts the user to input two numbers a and b, finds a%b, and prints the result. Raise TypeError if the user enters non-numeric values. Handle the exceptions when you call the function.
Q5:Design a simple interactive program that takes user input continuously and until the user decides to exit. Implement KeyboardInterrupt handling to gracefully exit the program when the user presses Ctrl+C.