 # Need insight on my use of try-except in python

Please, I just started learning python and I wrote a program that catches exceptions on user input. Please, can someone give me insight if I did it the correct way. The code below runs well but wondering if my style is usual.

``````#This little file tries to write a pay computation based on hours worked
#and the rate of pay. If hours worked is more than 40 hours, the rate
#is multiplied by 1.5 and increased.
Hours = input('Enter hours worked:')
try:
Hours = float(Hours)
except:
Rate = input('Enter the rate:')
try:
Rate = float(Rate)
except:
if Hours > 40 :
Rate = 1.5*Rate
Pay = Rate * Hours
print('The pay is',Pay)
``````

Thanks. I used two exception blocks, was wondering if there is a way to use just one.

## That is a possible solution for that challenge:

def pay():

``````while True:
try:
Hours = float(input('Enter hours worked:'))
except ValueError:
Hours = float(input('Enter hours worked:'))

try:
Rate = float(input('Enter the rate:'))
except ValueError:
Rate = float(input('Enter the rate:'))

if Hours > 40:
Pay = (Hours * Rate) + ((Hours - 40) * 1.5 * Rate)
else:
Pay = Hours * Rate

print("The pay is: %.2f" % Pay)
``````

In my opinion using two blocks in that case is the best way to solve that challenge. There is also a solution with only one “try-except” block. But you have to enter both values again if only one of them is wrong. I hope that helps you a little bit!

1 Like

It’s best to avoid `while True` in any language. There should always be a way to exit.

Personally, I would put the while loop around the input validation:

``````valid = False
while not valid:
try:
hours = float(input('Enter hours worked:'))
valid = True
except: