Python 代码正常工作,但不符合预期。试图根据输入打印每个月的天数——包括闰年。类型错误
我知道以前有人问过这个问题,但我的代码用于2月(02)的输入,但现在不是。我收到一个Python 代码正常工作,但不符合预期。试图根据输入打印每个月的天数——包括闰年。类型错误,python,python-3.x,list,Python,Python 3.x,List,我知道以前有人问过这个问题,但我的代码用于2月(02)的输入,但现在不是。我收到一个类型错误:不是所有在字符串格式化期间转换的参数我的代码执行时没有任何错误,但没有打印任何日期。感谢您的帮助,因为我还在学习 def isLeapyear(year): return (year % 4 == 0) and (year % 100 == 0) or (year % 400 == 0) def calcDays(): year = input('Please enter the year
类型错误:不是所有在字符串格式化期间转换的参数
我的代码执行时没有任何错误,但没有打印任何日期。感谢您的帮助,因为我还在学习
def isLeapyear(year):
return (year % 4 == 0) and (year % 100 == 0) or (year % 400 == 0)
def calcDays():
year = input('Please enter the year in XXXX format ')
month = input('Please enter the month in XX format ')
if month == ('01', '03', '05', '07', '08', '10', '12'):
print (31)
elif month == ('04', '06', '09', '11'):
print (30)
elif month == '02' and isLeapyear(year) == True:
print (29)
elif month == '02' and isLeapyear(year) == False:
print (28)
calcDays()
试试这个,你必须把年份改成int,在使用模式之前是str,我也改变了leapyear的条件
def isLeapyear(year):
return ((int(year) % 4 == 0) and (int(year) % 100 != 0)) or (int(year) % 400 == 0)
def calcDays():
year = input('Please enter the year in XXXX format ')
month = input('Please enter the month in XX format ')
if month == '01' or month == '03' or month == '05' or month == '07' or month == '08' or month == '10' or month == '12':
print(31)
elif month == '04' or month == '06' or month == '09' or month == '11':
print(30)
elif month == '02' and isLeapyear(year) == True:
print(29)
elif month == '02' and isLeapyear(year) == False:
print(28)
calcDays()
巫术。如果您想用python正确计算闰年,并且不想使用日历类,请使用:
def IsLeapYear(year):
if (year % 400 == 0)
return True
if (year % 100 == 0)
return False
if (year % 4 == 0)
return True
return False
或更优化:
def GregorianIsLeapYear(y):
if ((y % 4) != 0)
return False
if ((y % 100) != 0)
return True
return (y % 400) == 0
@这不是一个正确的答案。问题是他想
%
字符串,而不是问为什么要重新发明模块?为了将来的参考,如果你想检查一组精确的字符串输入是否匹配元组(或列表)中的一个字符串,你可以做一些类似的事情,例如如果月份在('01','03','05','07','08','10','12')
。嘿,这样比较变量是不可能的,是吗?你必须在(某物)中使用月份
对吗?或month=='01'或month=='02'或…
谢谢!我试过使用“或”,但不是正确的方式,所以它给了我一个错误。我只是注意到了一些事情,当我输入闰年时,一些闰年的结果是准确的,例如,2000年……但是其他年份,比如现在的2020年,却不准确?我已经检查过了,但我假设isLeapyear()中的计算一定有问题,对吗?您还希望year
作为int
使这些模数工作。。。