【问题标题】:Is there a way to shorten while loop code from user's input?有没有办法缩短用户输入的while循环代码?
【发布时间】:2015-04-11 06:09:37
【问题描述】:
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 循环缩短为一个循环?我知道有一种叫做“嵌套”的东西,但这似乎也很长。

对于user = user.split('/')list1 =list(user),有没有其他方法可以根据用户的输入创建一个列表?我尝试了user = user.split('/'),但尝试时似乎出现了一些错误。

【问题讨论】:

  • 请注意,您的算法存在根本缺陷 - 如果用户得到例如第一次年份错了,再更正年月错了,不会再查了。

标签: python input while-loop split


【解决方案1】:

与其自己写出来,不如把它交给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 “自带电池”;使用它们!使用中:

>>> 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 中使用特定的日期解析函数可以避免这个问题,而无需编写大量自己的检查代码。

【讨论】:

    【解决方案2】:
    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]))
      

    【讨论】:

      【解决方案3】:

      您的代码中存在一些问题,看来您对代码审查比其他任何事情都更感兴趣?

      这里有一些语义错误:

      2 月 30 日这样的日期会发生什么? 2015 年 2 月 30 日

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

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

      你的程序会打印出什么?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 2019-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多