Rohail
Rohail

Reputation: 75

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

Upvotes: 1

Views: 157

Answers (2)

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85432

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

Upvotes: 4

alexis
alexis

Reputation: 50190

The try-except block is there because the user might enter something that's not a valid float. E.g., "none". In that case, python will throw a ValueError. Using an unrestricted except is very bad style, so the code should have read

try:
    score = float(inp)
except ValueError:
    score = -1

It's set to -1 because the rest of the code treats negative scores as illegal inputs, so anything illegal will get the point across without terminating the program.

Upvotes: 2

Related Questions