Search code examples
pythonpython-3.xtry-catchexcept

Use of try and except in this python in this program


Can you please tell me why try and except is used in the following code? Why score=-1? I mean why only -1

inp = input('Enter score: ')
    try:
        score = float(inp)
    except:
        score = -1

if score > 1.0 or score < 0.0:
       print ('Bad score')
   elif score > 0.9:
     print ('A')
   elif score > 0.8:
     print ('B')
   elif score > 0.7:
     print ('C')
   elif score > 0.6:
     print ('D')
   else:
     print ('F')

Cant we use the following code which has no try and except commands.

 score = float(input('Enter score: '))
   if score > 1.0 or score < 0.0:
       print ('Bad score')
   elif score > 0.9:
       print ('A')
   elif score > 0.8:
       print ('B')
   elif score > 0.7:
       print ('C')
   elif score > 0.6:
       print ('D')
   else:
       print ('F')

Solution

  • If the user enters something that cannot be converted into a float, the program would stop with an exception. The try catches this and uses a default value.

    This would work:

    inp = input('Enter score: ')
    try:
        score = float(inp)
    except ValueError:
        print('bad score')
    

    Your version:

    score = float(input('Enter score: '))
    if score > 1.0 or score < 0.0:
         print ('Bad score')
    

    would throw a ValueError on this line float(input('Enter score: ')) if the user would enter abc for example. Your program would stop before you can print Bad score'.