Python - 多输入验证

时间:2016-04-06 01:48:29

标签: python validation loops

我正在使用一系列嵌套循环编写一个付费计算器程序。一切正常,但我必须确保在指定日期工作的小时数输入介于0和24之间。这是我对该部分的代码,我尝试了多种不同的选项,但它们都会使程序崩溃或根本无法识别。任何帮助将不胜感激!

这是相关代码:

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)

如果您需要更广泛的外观,这是整个代码:

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)

2 个答案:

答案 0 :(得分:1)

您的代码没有检查有效的小时输入(除非您因为崩溃而将其删除等)。这是一种方法:

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

答案 1 :(得分:0)

通常更好地使用模块化工作,使用函数执行操作。此代码可能有效,而且更具可读性:

file.read()
相关问题