简体   繁体   English

在列表Python中选择元素

[英]Selecting elements in list Python

I am trying to select elements in a list containing the number of days in each month and add those days onto a variable containing a total. 我试图在包含每个月中天数的列表中选择元素,并将这些天添加到包含总计的变量中。

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)

EDIT: 编辑:

Ok, I fixed the issue with the input, however with this code nothing is being added to days, any ideas why? 好的,我已经解决了输入的问题,但是使用此代码,几天没有添加任何东西,为什么有想法?

Thanks. 谢谢。

In addition to the problem stated by Kieleth, your loop does not use the indices you expected. 除了Kieleth指出的问题外,循环还没有使用您期望的索引。 We are now in october ( nowmonth = 10 ), say I answer 4 for april. 我们现在在10月( nowmonth = 10 ),说我4月回答4

for c in range(months[intmonth-1], months[nowmonth-1]):

gives intmonth-1 = 3 , months[intmonth-1] = 30 , nowmonth-1 = 9 , months[nowmonth-1] = 31 => c gets the value 30 !!! 给出intmonth-1 = 3months[intmonth-1] = 30nowmonth-1 = 9months[nowmonth-1] = 31 => c获得值30

So you code should be : 所以你的代码应该是:

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)

But the method to find those kind or errors if quite simple : print is your friend !!! 但是找到那些类型或错误的方法(如果很简单): 打印是您的朋友

If you simply had written: 如果您只是写过:

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)

it would have been evident that you did not go through the loop 显然您没有经历循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM