有没有办法缩短用户输入的循环代码?

时间:2015-04-11 06:09:38

标签: python input while-loop split

def main():

  month = 0
  date = 0
  year = 0
  date = [month, date, year,]
  user = input("Enter according to mm/dd/yy: ")
  user = user.split('/')
  list1 = list(user)
  months = {'1': 'January', '2': 'Feburary', '3': 'March', '4': 'April', '5': 'May', '6': 'June',
          '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}

  while int(list1[0]) > 12  or int(list1[0]) < 1:
    print("Month is incorrect.")
    user = input("Enter according to mm/dd/yy:")
    user = user.split('/')
    list1 = list(user)

  while int(list1[1]) > 31 or int(list1[1]) < 0:
    print("Date is incorrect.")
    user = input("Enter according to mm/dd/yy:")
    user = user.split('/')
    list1 = list(user)

   while int(list1[2]) > 15 or int(list1[2]) < 15:
    print("Year is incorrect.")
    user = input("Enter according to mm/dd/yy:")
    user = user.split('/')
    list1 = list(user)

  print(months[list1[0]], list1[1], (",") , ("20") + list1[2])



main()

有没有办法将while循环缩短为一个循环?我知道那里有一些名为&#34; nesting&#34;,但这似乎也很长。

对于user = user.split('/')list1 =list(user),还有另一种方法可以根据用户的输入制作列表吗?我尝试了user = user.split('/'),但是当我尝试时似乎有一些与之相关的错误。

3 个答案:

答案 0 :(得分:2)

不要将自己全部写出来,而是将其移植到datetime

from datetime import datetime

def main():
    while True:
        try:
            date = datetime.strptime(
                input("Enter according to mm/dd/yy: "),
                '%m/%d/%y',
            )
        except ValueError:
            print('Invalid input, please try again.')
        else:
            break
    print(date.strftime('%B %d, %Y'))

Python来自&#34;包含电池&#34; ;使用它们!使用中:

>>> main()
Enter according to mm/dd/yy: 31/05/15
Invalid input, please try again.
Enter according to mm/dd/yy: 05/31/2015
Invalid input, please try again.
Enter according to mm/dd/yy: 05/31/15
May 31, 2015

在简化现有方法方面,我建议如下:

#  Define valid inputs
DAYS = set(range(1, 32))  # Note that not all months have all of these...
MONTHS = {1: 'January', 2: 'February', ...}
YEARS = set(range(2015, 2016))

def main():
    while True:
        date = input("Enter according to mm/dd/yy: ")
        try:
            month, day, year = map(int, date.split("/"))
        except ValueError:
            print("Not valid input.")  # not numbers, or didn't have two slashes
            continue
        if day not in DAYS:
            print("Not a valid date.")
            continue
        # Similar for months, years
        break
    print("{month} {day:02d}, 20{year:02d}".format(
        month=MONTHS[month],
        day=day,
        year=year,
    ))

然而,当它确实不是可接受的日期时,这将接受例如"02/31/15"作为完全有效的输入;使用Python中的特定日期解析函数可以避免这个问题,而无需编写大量自己的检查代码。

答案 1 :(得分:1)

months = {'1': 'January', '2': 'Feburary', '3': 'March', '4': 'April', '5': 'May', '6': 'June',
          '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}

def main():      
  while True:
    user = input("Enter according to mm/dd/yy: ")
    user = user.split('/')
    list1 = list(user)
    if not 1 <= int(list1[0]) <= 12:
        print("Month is incorrect.")
        continue
    if not 0 <= int(list1[1]) <= 31:
        print("Day is incorrect.")
        continue 
    if not 15 <= int(list1[2]) <= 15:
        print("Year is incorrect.")
        continue
    break

  print(months[list1[0]], list1[1], (",") , ("20") + list1[2])

注释

  1. 在新版本中,input语句只出现一次。

  2. 代码的原始版本接受0天。我在修订后的代码中继续说道。

  3. 有些人可能会更容易阅读的print语句的等效表单是:

    print('{} {}, 20{}'.format(months[list1[0]], list1[1], list1[2]))
    

答案 2 :(得分:0)

您的代码中存在一些问题,您似乎对代码审核比其他任何内容更感兴趣吗?

这里有一些语义错误:

2月30日这样的日期会发生什么?二零一五年二月三十〇日

假设我输入了这些值的字符串。

Enter according to mm/dd/yy:
>> 12/01/14
Year is incorrect.
>> 99/99/15

你的节目打印出来的是什么?