2011-10-22 51 views
1

我试图让用户输入一个出生日期,然后在这些数字中添加个人整数。另外,如果任何这些数字的总和大于或等于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") 
+0

您的编辑:一般来说,你应该[问一个新的问题](http://stackoverflow.com/questions/ask)如果它不是原来的一个子问题。 – jfs

+0

指定是否使用Python 2.x或3.x.你的代码看起来像Python 3. – jfs

回答

2

工作太多。

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

请注意,这会为小于1

0

号失败你可以做到这一点

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

最后的总和必须小于10. – jfs

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 /除外,则:

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)) 
+0

非常感谢!超级有用。不幸的是,我不认为我们可以尝试/除了 – user979616

+0

@ user979616:我已经添加变种没有尝试/除了。 – jfs