Checkpoint 4.7.1.
Q-2: The
try / except feature is more or less a(n) _______ for your code.
input and int functions to read and parse an integer number entered by the user. We also saw how treacherous doing this could be:>>> prompt = "What is the air velocity of an unladen swallow?\n"
>>> speed = input(prompt)
What is the air velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10:
>>>
Enter Fahrenheit Temperature:72 that is 22.22222222222222 degrees Celsius.
Enter Fahrenheit Temperature:fifty
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahrenheit = float(input_str)
ValueError: could not convert string to float: 'fifty'
try and except is that you know that some sequence of instruction(s) may have a problem and you want to add some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error.try and except feature in Python as an “insurance policy” on a sequence of statements.try / except feature is more or less a(n) _______ for your code.
try block. If all goes well, it skips the except block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block.Enter Fahrenheit Temperature:72 22.22222222222222
except block:Enter Fahrenheit Temperature:fifty Please enter a number.
try statement is called catching an exception. In this example, the except clause prints an error message. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.try/except feature is used to catch ________.