gpt4 book ai didi

python - While 循环太早中断了。

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:14 31 4
gpt4 key购买 nike

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()

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

最佳答案

您可以以不同的方式安排:

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)

关于python - While 循环太早中断了。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332310/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com