关于for循环的求和

时间:2011-10-22 18:22:34

标签: python loops

我正在尝试让用户输入出生日期,然后在这些数字中添加单个整数。此外,如果这些数字中的任何一个的总和大于或等于10,则循环重复并且该过程再次针对该值运行。到目前为止,这是我的代码

if (sumYear >= 10):
    sumYear2=0
    for num in str(sumYear):
        sumYear2 += int(num)
print(sumYear2)

但是我觉得这样做会更好。如果有某种方式,我将不必使用像sumYear2那样伟大的东西。注意,我认为我不能使用sum()函数。

谢谢大家的帮助。我有一个问题。我不确定为什么在将月份设置为02而将日期设置为30

时,此代码未被评估
while True:
        year=input("Please enter the year you were born: ")
        month=input("Please enter the month you were born: ")
        day=input("Please enter the day you were born: ")
        if(int(month)==2 and int(day)<=29):
            break
        elif(int(month)==1 or 3 or 5 or 7 or 8 or 10 or 12 and int(day)<=31 ):
            break
        elif(int(month)==4 or 6 or 9 or 11 and int(day)<=30):
            break
        else:
            print("Please enter a valid input")

3 个答案:

答案 0 :(得分:2)

工作太多了。

singledigitsum = (int(inputvalue) - 1) % 9 + 1

请注意,对于小于1的数字,这将失败。

答案 1 :(得分:1)

@Ignacio Vazquez-Abrams's answer提供了公式。但如果没有,那么您的代码作为循环而不使用sumYear2可能看起来像:

while sumYear >= 10:
      sumYear = sum(map(int, str(sumYear)))

如果您不被允许使用sum(作业),那么:

while sumYear >= 10:
      s = 0
      for d in str(sumYear):
          s += int(d)
      sumYear = s

对于假设Python 3的第二个问题:

while True:
    try:
        year  = int(input("Please enter the year you were born: "))
        month = int(input("Please enter the month you were born: "))
        day   = int(input("Please enter the day you were born: "))
        birthday = datetime.date(year, month, day)
    except ValueError as e:
        print("error: %s" % (e,))
    else:
        break

如果您不允许使用try / except:

year  = get_int("Please enter the year you were born: ",
                datetime.MINYEAR, datetime.MAXYEAR)
month = get_int("Please enter the month you were born: ",
                 1, 12)
day   = get_int("Please enter the day you were born: ",
                1, number_of_days_in_month(year, month))
birthday = datetime.date(year, month, day)    

get_int()

def get_int(prompt, minvalue, maxvalue):
    """Get an integer from user."""
    while True:
        s = input(prompt)
        if s.strip().isdigit():
           v = int(s)
           if minvalue <= v <= maxvalue:
              return v
        print("error: the input is not an integer in range [%d, %d]" % (
            minvalue, maxvalue))

number_of_days_in_month()

# number of days in a month disregarding leap years
ndays = [0]*13
ndays[1::2] = [31]*len(ndays[1::2])  # odd months
ndays[::2] = [30]*len(ndays[::2])    # even months
ndays[2] = 28 # February
ndays[8] = 31 # August 
# fill other months here ...

def number_of_days_in_month(year, month):
    return ndays[month] + (month == 2 and isleap(year))

答案 2 :(得分:0)

你可以这样做

>>> d=123456
>>> sum(int(c) for c in str(d))
21