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:
    print('Enter a number please!\n')
Rate = input('Enter the rate:')
try:
    Rate = float(Rate)
except:
    print('Enter a number please!') 
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:
        print('Enter a number please!\n')
        Hours = float(input('Enter hours worked:'))

    try:
        Rate = float(input('Enter the rate:'))
    except ValueError:
        print('Enter a number please!\n')
        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:
    print('Enter a number please!\n')
2 Likes

But if you use a break statement, there would be nothing wrong with while True

You can, but I still wouldn’t recommend it. It’s not a great practice and it’s not really common in professional code. Its better to have a variable that holds the loop exit condition and loop while the exit condition is not true.

1 Like

OK. Thanks. I got the message.