0

I am new to Python. For my program, I want to display a message when the user enters a wrong input, such as characters and negative numbers, and get the user to provide input again. I know how to do that using try and except for the exception of character inputs, but I am still figuring out how to use it for negative number inputs. Or is there a better way to do it?

def CalPay(hrs,rate): 
    print('Please enter number of hours worked for this week:', hrs)
    print('What is hourly rate?', rate)
    try:  
        hrs = float(hrs)
        hrs>=0
    except: 
        print('You entered wrong information for hours.')
        while True:
            try:
                hrs=float(input('Please enter number of hours worked for this week:'))
            except:
                print('You entered wrong information for hours.')
                continue 
            else:
                break
    try: 
        rate = float(rate)
        rate>=0
    except:
        print('You entered wrong rate information.')
        while True:
            try:
                rate=float(input('What is hourly rate?'))
            except:
                print('You entered wrong rate information.')
                continue
            else:
                break
    if hrs > 60:
        pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
        print('Your pay for this week is:', '$'+str(pay))
    elif hrs > 40:
        pay=((hrs-40)*1.5*rate)+(rate*40)
        print('Your pay for this week is:', '$'+str(pay))
    else:
        pay=rate*hrs
        print('Your pay for this week is:', '$'+str(pay))
  • Welcome to SO! How about a simple `if` statement for this? As an aside, Pokemon Exceptions are considered poor practice. Better to catch the exception you mean to catch (`ValueError`) instead of catching 'em all. – ggorlen Apr 19 '20 at 02:37
  • As ggorlen said, try add a `if` to check if the number is negative: `if hrs < 0: print('You entered negative number.')` – Frank Apr 19 '20 at 02:41
  • Be careful about using a bare except like that, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. Also, variable and function names should generally follow the `lower_case_with_underscores` style. – AMC Apr 19 '20 at 03:01

2 Answers2

0

You could just use the while loop to check if the hrs or rate is less than or equal to zero. Something like this:

def CalPay(hrs,rate): 
    print('Please enter number of hours worked for this week:', hrs)
    print('What is hourly rate?', rate)
    hrs = float(hrs)

    while hrs <= 0: 
        print('You entered wrong information for hours.')
        hrs=float(input('Please enter number of hours worked for this week:'))

    rate = float(rate)

    while rate <= 0:
        print('You entered wrong rate information.')
        rate=float(input('What is hourly rate?'))

    if hrs > 60:
        pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
        print('Your pay for this week is:', '$'+str(pay))
    elif hrs > 40:
        pay=((hrs-40)*1.5*rate)+(rate*40)
        print('Your pay for this week is:', '$'+str(pay))
    else:
        pay=rate*hrs
        print('Your pay for this week is:', '$'+str(pay))
bmcculley
  • 2,048
  • 1
  • 14
  • 17
0

For this example, simple ifs would be sufficient, but if you have lots of questions to ask and a variety of types and conditions, you could do something like this:

def ask(question, help_, type_, *conditions):
    try:
        answer = type_(input(question))
        if any(not cond(answer) for cond in conditions):
            raise ValueError
        return answer
    except TypeError, ValueError:
        print(help_)
        return ask(question, help_, type_, *conditions)

question is the prompt for input, help_ is printed if failure occurs, type_ is a function that marshalls the input string to a desirable type, and conditions is a variable number of boolean-returning functions - all of which must be true. If the type or conditions fail, the function prints help texts and recurses.

hrs = ask(
    "Please enter the number of hours worked for this week: ", 
    "You entered incorrect information for hours.", 
    float, 
    lambda x: x >= 0)
)
....
time = ask(
    "What day is it?"
    "It has to be the current month and after now... idk",
    lambda s: dt.datetime.strptime(s, "%b %d %Y")
    lambda d: d > dt.datetime.now(),
    lambda d: d.month == dt.datetime.now().month,
)
modesitt
  • 7,052
  • 2
  • 34
  • 64