我正在尝试选择包含每月天数的列表中的元素,并将这些天添加到包含总计的变量中。
from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
inmonth = str(float(input("month")))
intmonth = int(inmonth[0])
nowmonth = (date.today().month)
days = 0
if intmonth < nowmonth:
for c in range(months[intmonth-1], months[nowmonth-1]):
days = days + months[c]
print(days)
编辑:
好的,我用输入修复了这个问题,但是这个代码什么都没有添加到几天,任何想法为什么?
感谢。
答案 0 :(得分:0)
除了Kieleth所述的问题之外,您的循环不会使用您期望的索引。
我们现在是十月(nowmonth = 10
),比如我4月回答4
。
for c in range(months[intmonth-1], months[nowmonth-1]):
提供intmonth-1 = 3
, months[intmonth-1] = 30
,nowmonth-1 = 9
, months[nowmonth-1] = 31
=&gt; c
获取值30
!!!
所以你的代码应该是:
from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
intmonth = int(input("month")) # fixes the problem stated by Kieleth
nowmonth = (date.today().month)
days = 0
if intmonth < nowmonth:
for c in range(intmonth-1, nowmonth-1):
days = days + months[c]
print(days)
但是找到那些类型或错误的方法非常简单: print是你的朋友 !!!
如果您只是写了:
from datetime import date
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
inmonth = str(float(input("month")))
intmonth = int(inmonth[0])
print(inmonth, intmonth) # control input
nowmonth = (date.today().month)
days = 0
if intmonth < nowmonth:
for c in range(months[intmonth-1], months[nowmonth-1]):
print (c, days) # a spy per iteration
days = days + months[c]
print(days)
很明显,你没有经历循环