我正在制作一个基本的日期转换器,我需要在每次用户输入无效日期时更新日期,并要求再次输入。从下面的这个函数,我需要返回对象日和年。
def day_valid (month, dates, feb_day, month_days):
day = int(dates[2:4])
while month_days == 31 and day > 31:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == 31 and day < 32:
break
while month_days == 30 and day > 30:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == 30 and day < 31:
break
while month_days == feb_day and day > feb_day:
print ("Invalid day input.")
print()
dates = input_date()
day = int(dates[2:4])
if month_days == feb_day and day <= feb_day:
break
return day
当用户以MMDDYYYY格式键入00102002时,没有月份。因此,系统会提示用户再次输入,输入01102005.代码仍显示日期为1月10日 2002 而不是 2005 。
如果有人需要澄清代码,请询问!
我的主要职能:
def main():
loop = "Y"
print()
print("Welcome to Date Converter!")
print()
while loop.upper () == "Y" :
dates = input_date()
year = int(dates[4:])
month = month_valid(dates)
feb_day = feb_days(year)
month_days = month_Days(month, feb_day)
day = day_valid(month, dates, feb_day, month_days)
month_str = month_names(month)
print()
print("The date is " + str(day) + " " + month_str + " " + str(year))
loop = str(input ("Do you want to re-run this program? Y/N: "))
main()
答案 0 :(得分:1)
这听起来首先像XY Problem:有人想做X,并提出需要做Y的解决方案。他们需要Y的帮助,所以请求帮助做Y.但事实证明Y不是一个合适的解决方案。通过识别XY问题并询问如何做X,这个人可以获得更好的帮助并更深入地了解X.
XY问题也经常看起来像家庭作业问题,因为那些通常具有以下形式&#34;通过做Y&#34;编写一个执行X的程序。
可以提出你想要做X的问题并试图用Y来解决它。
无论如何,这就是为什么你可能会得到低效的答案。我会努力:)
无论如何,继续Y问题:)
有一种可读性实践认为元组是有害的,因为你不知道元组中项目的目的是什么。考虑改为创建一个包含东西的对象,每个对象都有自己的属性,然后返回它。
由于您声明需要day
和year
返回:
class DayAndYear(object):
def __init__(self, day, year):
self.day = day
self.year = year
这就是你如何在不制作元组的情况下做到这一点,它增加了你的程序的可读性,例如它。
现在,继续使用未说明的X问题:
month_valid
做了什么,feb_days
返回给定年份2月份的天数,month_Days
返回给定月份的天数,而不是2月,似乎你想要一个能检查字符串是否是有效MMDDYYYY字符串的函数。
def is_valid_date(s):
"""Checks if the given date is a valid MMDDYYYY string.
Args:
s (str): A date to check.
Returns:
bool: True if the date is valid, False otherwise.
"""
if len(s) != 8:
return False
try:
date = int(s[:2])
month = int(s[2:4])
year = int(s[4:])
except ValueError:
return False
if month < 1 and month > 12:
return False
if month == 2:
days_in_month = days_in_february(year)
else:
days_in_month = days_in_month(month)
return date >= 1 and date <= days_in_month
def print_date(s):
"""Prints the given MMDDYYYY date, assuming it has already been checked for validity.
Args:
s (str): A date to print.
"""
print("The date is {:d} {:s} {:d}.".format(
int(s[2:4]), month_name(int(s[:2])), int(s[4:])))
我想强调一些使您的程序更好阅读的一般技巧:
简短的概念:
month_Days
&#34; vs&#34; feb_days
&#34;)