虽然循环过早破裂。

时间:2014-04-28 04:05:53

标签: python loops while-loop

import datetime


def main():
    date_string = input('Enter a date in mm/dd/yy format: ')
    date_list = date_string.split('/')
    month = int(date_list[0])
    day = int(date_list[1])
    year = int(date_list[2])
    while month < 1 or month > 12:
        print('Month entered is out of range')
        date_string = input('Re-enter a date in mm/dd/yy format: ')
        date_list = date_string.split('/')
        month = int(date_list[0])
        day = int(date_list[1])
        year = int(date_list[2])
    while day < 1 or day > 31:
        print('Day entered is out of range')
        date_string = input('Re-enter a date in mm/dd/yy format: ')
        date_list = date_string.split('/')
        month = int(date_list[0])
        day = int(date_list[1])
        year = int(date_list[2])
    while year != 13:
        print('Year does not represent 2013')
        date_string = input('Re-enter a date in mm/dd/yy format: ')
        date_list = date_string.split('/')
        month = int(date_list[0])
        day = int(date_list[1])
        year = int(date_list[2])
    print(month, day, year)
main()

当我运行程序并输入无效的月份和日期时,它会向下进行直到年度验证,并且即使输入对其他输入之一无效,也会继续发布该提示。

2 个答案:

答案 0 :(得分:1)

你可以用不同的方式安排:

while True:
    date_string = input('Enter a date in mm/dd/yy format: ')
    date_list = date_string.split('/')
    month = int(date_list[0])
    day = int(date_list[1])
    year = int(date_list[2])
    if month < 1 or month > 12:
        print('Month entered is out of range')
    elif day < 1 or day > 31:
        print('Day entered is out of range')
    elif year != 13:
        print('Year does not represent 2013')
    else:
        break
print(month, day, year)

答案 1 :(得分:0)

重新开始。

你不需要三个小循环。你想要一个大的while循环(while not success)和三个if语句进行三次检查,如果有任何一个失败,将success设置为false。