Python 3.x 蟒蛇三号:“;ValueError:以10为基数的int()的文本无效:';2.0'&引用;
我的代码如下:Python 3.x 蟒蛇三号:“;ValueError:以10为基数的int()的文本无效:';2.0'&引用;,python-3.x,Python 3.x,我的代码如下: def MonthID(month): """INPUT: 'month' is the amount of months after the beginning of the computed rotation. OUTPUT: Returns the month ID composed by the 3 first letters of the month name and the amount of years after the
def MonthID(month):
"""INPUT:
'month' is the amount of months after the beginning of the computed rotation.
OUTPUT:
Returns the month ID composed by the 3 first letters of the month
name and the amount of years after the beginning of the rotation.
"""
year = str( (month//12)+1 )
if month % 12 == 0:
return "dec"+ str( int(year) - 1 )
elif month % 12 == 1:
return "jan"+year
elif month % 12 == 2:
return "feb"+year
。。。
等等
随机地,当year
超过1时,我会得到以下错误:ValueError:int()的文本无效,基数为10:'2.0'
。好。。。2.0不是一个数字吗
直到现在我还没有问题,功能正常工作了好几天。。。
我试图分解我的“十二月线”,如下所示,但没有结果:
year = int(year) - 1
return "dec"+ str( year )
还有其他人犯过这种错误吗?
我想问题可能来自调用函数的框架,但我无法解决。。。我只需将此功能与
打印
一起使用,即可轻松了解代码的时间位置。如果月份
是浮动,月份//12
也是浮动。这使得month//12+1
afloat
;当您将其转换为字符串时,它将变成'2.0'
。解释器抱怨是对的,因为'2.0'
对于整数来说确实是无效的文本
这意味着在代码的某个地方有一个使用浮点参数调用MonthID
,可能与加载数据的方式有关。因此,一个简单的
year = str( int(month//12)+1 )
我们应该做到这一点。无论如何,您应该考虑重新构造代码,使其更具可读性,更不容易出错。考虑将月份名称声明为函数之外的元组:
month_names = ('dec', 'jan', 'feb', 'mar', <other months here...>)
或:
嗯。。。我资助了一个变通办法。目前看来,这是可行的:
year = (month//12)+1
if month % 12 == 0:
year = year - 1
return "dec" + str(year)
elif month % 12 == 1:
return "jan"+ str(year)
elif month % 12 == 2:
return "fev"+ str(year)
...
etc
...
def MonthID(month):
year = int(month-1)//12 + 1
return month_names[int(month) % 12] + str(year)
year = (month//12)+1
if month % 12 == 0:
year = year - 1
return "dec" + str(year)
elif month % 12 == 1:
return "jan"+ str(year)
elif month % 12 == 2:
return "fev"+ str(year)
...
etc
...