मराठी

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 > ')

Advertisements
Advertisements

प्रश्न

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 = 0
कोड लेखन
Advertisements

उत्तर

The code may crash in the following situations:

  • loop is not initialized before while loop == 1, causing a NameError.
  • The shown try/except blocks have incorrect indentation and arrangement, causing a SyntaxError before execution.
  • In Python 3, input() returns strings; therefore a - b causes a TypeError unless the inputs are converted to numbers.
  • Invalid numeric expressions may cause ValueError or SyntaxError, depending on the Python version and input method.
  • Pressing Ctrl-C raises KeyboardInterrupt, which is not handled.
  • Pressing Ctrl-D or Ctrl-Z may raise EOFError, 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 = 0
shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५७]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 8 Exception Handling & Generate Functions
EXERCISE | Q 4. | पृष्ठ १५७
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×