Advertisements
Advertisements
Question
Find out the situation(s) in which the following code may crash.
while loop == 1:
try:
a = input('Enter a number to subtract from > ')
b = input ('Enter the number to subtract > ')
except NameError:
print "\nYou cannot subtract a letter"
continue
except SyntaxError:
print "\nPlease enter a number only."
continue
print a - b
try:
loop = input('Press 1 to try again > ')
except (NameError,SyntaxError):
loop = 0Code Writing
Advertisements
Solution
The code may crash in the following situations:
loopis not initialized beforewhile loop == 1, causing aNameError.- The shown
try/exceptblocks have incorrect indentation and arrangement, causing aSyntaxErrorbefore execution. - In Python 3,
input()returns strings; thereforea - bcauses aTypeErrorunless the inputs are converted to numbers. - Invalid numeric expressions may cause
ValueErrororSyntaxError, depending on the Python version and input method. - Pressing
Ctrl-CraisesKeyboardInterrupt, which is not handled. - Pressing
Ctrl-DorCtrl-Zmay raiseEOFError, which is also not handled.
A safer Python 3 version is:
loop = 1
while loop == 1:
try:
a = float(input("Enter a number to subtract from: "))
b = float(input("Enter the number to subtract: "))
print(a - b)
except ValueError:
print("Please enter numbers only.")
except EOFError:
print("Input ended.")
break
try:
loop = int(input("Press 1 to try again: "))
except ValueError:
loop = 0shaalaa.com
Is there an error in this question or solution?
