简体   繁体   中英

Python - Multi Input Validation

I'm writing a pay calculator program using a series of nested loops. Everything works except I have to make sure that the input for number of hours worked on the specified day is between 0 and 24 inclusive. This is the code I have for that section, I've tried multiple different options but they all either crash the program or aren't recognised at all. Any help would be appreciated!

This is the related code:

for x in range(0, weeks):
        for y in days:
            while True:
                print ("Enter the number of hours for Week", x+1, y, ":")
                try:
                    hours = int(input())
                except ValueError:
                    print ("Invalid: Enter a positive integer")
                    continue
                else:
                    break;
            if y == 'Saturday':
                newRate = satRate
            elif y == 'Sunday':
                newRate = sunRate
            else:
                newRate = baseRate

            rate += (hours * newRate)

This is the whole code if you need a more wide look:

baseRate = -1
while baseRate < 1:
    baseRate = float(input("Enter the base pay rate: "))
    if baseRate < 1:
        print("Invalid: Enter a non-negative amount")
satRate = baseRate * 1.5
sunRate = baseRate * 2
pay = 0
rate = 0
hours = -2
weeks = -1
while weeks < 1:
    while True:
        try:
            weeks = int(input("Enter the number of weeks: "))
        except ValueError:
            print("Invalid: Enter a positive integer")
            continue
        else:
            break
    if weeks < 1:
        print("Invalid: Enter a positive integer")

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for x in range(0, weeks):
    for y in days:
        while True:
            print ("Enter the number of hours for Week", x+1, y, ":")
            try:
                hours = int(input())
            except ValueError:
                print ("Invalid: Enter a positive integer")
                continue
            else:
                break;
        if y == 'Saturday':
            newRate = satRate
        elif y == 'Sunday':
            newRate = sunRate
        else:
            newRate = baseRate

        rate += (hours * newRate)
pay = (round(rate, 2))
av = pay/weeks
average = round(av,2)

print("Total pay is: ", pay)
print("Average pay per week is: ", average)

Your code doesn't check for valid hours input (unless you removed it due to it crashing, etc). Here one way to do it:

try:
    hours = int(input())
    while not 0 <= hours <= 24:
                print ("Invalid input, hours must be between 0 and 24 inclusive.")
                print ("Try again")
                hours = int(input())
        except ValueError:
            print ("Invalid: Enter a positive integer")
            continue

It is usually better to work more modular, using functions for your actions. This code may work and it's much more readable:

def get_baserate():
    rate = input('Base rate:')
    try:
        rate = float(rate)
        if not rate > 0:
            print 'Rate must be positive'
            return get_baserate()
        return rate
    except TypeError:
        print 'Rate must be a positive number'
        return get_baserate()

def get_weeks():
    weeks = input('Number of weeks:')
    try:
        weeks = int(weeks)
        if not weeks > 0:
            print 'A positive number must be entered'
            return get_weeks()
        return weeks + 1
    except TypeError:
        print 'An integer must be entered'
        return get_weeks()

def get_hours(week, day):
    hours = input('Enter number of hours worked on %s of week %s:' % (day, week))
    try:
        hours = int(hours)
        if not 0 <= hours <= 24:
            print 'A number between 0-24 must be entered'
            return get_hours(day)
        return hours
    except TypeError:
        print 'An integer must be entered'
        return get_hours(day)

def get_payday(rate, hours, day):
    rate = 2*rate if day == 'Sunday' else 1.5*rate if day == 'Saturday' else rate
    return hours*rate

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

rate = get_baserate()
weeks = get_weeks()
total_payday = 0
for week in range(1, weeks):
    for day in days:
        hours = get_hours(week, day)
        total_payday += get_payday(rate, hours, day)
print 'Your total pay is: %s' % total_payday

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM