在列表Python中选择元素
我试图在包含每月天数的列表中选择元素,并将这些天数添加到包含总数的变量中在列表Python中选择元素,python,list,date,Python,List,Date,我试图在包含每月天数的列表中选择元素,并将这些天数添加到包含总数的变量中 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 < nowmon
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)
编辑:
好的,我用输入修复了这个问题,但是用这段代码,没有任何东西被添加到天中,你知道为什么吗
谢谢。除了Kieleth指出的问题之外,您的循环没有使用您期望的索引。 我们现在是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=>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)
但是找到这些类型或错误的方法非常简单:打印是你的朋友
如果你只是写了:
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)
很明显,您没有经历循环Try months[int'03']。您正在计算两个日期之间的天数吗?请尝试:days=days+monthsrev[intc]是的,如果输入的年份大于当前年份,这只是代码的一部分。我没有使用datea dateb函数就这么做了。@user2975192:请把你的发现写下来,作为你问题的解决方案,并接受它。许多其他人也会有类似的问题,因此如果每个满意的客户都不留痕迹地离开,那么问题就不存在了