-1

When the user gives wrong input for tax_rate, it should ask user the correct input for that variable, but instead it is starting from first, asking the hr_rate input which is already received.

while True:
    try:
        hr_rate = float(input("Enter Hourly Rate: "))
        emp_ot_rate = float(input("Enter Overtime Rate: "))
        tax_rate = float(input("Enter Standard Tax Rate: "))
        ot_tax_rate = float(input("Enter Overtime Tax Rate: "))

    except Exception:
        print("Invalid entry, please retry")

Output:

Enter Hourly Rate: abc
Invalid entry, please retry
Enter Hourly Rate: 10.2
Enter Overtime Rate: 20.25
Enter Standard Tax Rate: abc
Invalid entry, please retry
Enter Hourly Rate:

The last line should ask for Standard Tax Rate again.

martineau
  • 119,623
  • 25
  • 170
  • 301
Mathew
  • 61
  • 1
  • 8
  • 7
    Write a function? – Brian61354270 Mar 10 '21 at 21:00
  • yep, an ask-for-a-float function that takes the prompt message and returns a float. In general, ask yourself what parts are the same and what parts need to be different. In this case it's just the prompt text. – Dave S Mar 10 '21 at 21:04
  • Thanks. Actually I tried using function as well, but the problem was that whenever user gives a wrong input, it starts running from first. – Mathew Mar 10 '21 at 21:18
  • Your `try`/`except` is too broad — so you need to effectively apply it to each input separately (perhaps by creating a generic get input function). – martineau Mar 10 '21 at 21:55

2 Answers2

2

Whenever you see repetitive code, it is generally the case of defining a function that performs the same task but with the appropriate differences based on the given argument(s):

def userInput(variable):
    while True:
        try:    
            user_input = float(input(f"Enter {variable}: "))
            break
        except Exception:
            print("Please enter any numbers")
        return user_input

This function will perform the same task but the input prompt will change according to the variable argument; e.g you can call it with 'Hourly Rate':

hr_rate = userInput("Hourly Rate")

and it will prompt the user with the correct sentence:

>>>Enter Hourly Rate: 
Max Shouman
  • 1,333
  • 1
  • 4
  • 11
-1

From @Brian's comment above, and at the risk of doing someone's homework for them...

def float_input(prompt):
    '''Prompt user with given <prompt> string.'''
    while True:
        try:    
            return float(input("Enter Hourly Rate: "))
        except ValueError:  # Make exceptions as specific as possible  
            print("Please enter any numbers")

hr_rate = float_input("Enter Hourly Rate: ")
emp_ot_rate = float_input("Enter Overtime Rate: ")
tax_rate = float_input("Enter Standard Tax Rate: ")
ot_tax_rate = float_input("Enter Overtime Tax Rate: ")
Sarah Messer
  • 3,592
  • 1
  • 26
  • 43