关于用for循环求和

发布于 2024-12-11 09:06:49 字数 935 浏览 0 评论 0原文

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

I'm trying to get the user to input a birth date and then add the individual ints in those numbers. Also, if a sum of any of these digits is greater than or equal to 10, the loop repeats and the process runs again for the value. Here's my code so far

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

This works however I think it would be better done as a loop. And if there's some way I won't have to use something like sumYear2 that would be great. Note, I don't think I can use the sum() function.

Thanks guys for the help. I'm having an issue though. I'm not sure why this code isn't being evaluated when I provide the month as 02 and the day as 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")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一个人的夜不怕黑 2024-12-18 09:06:49

工作量太大了。

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

请注意,对于小于 1 的数字,此操作将会失败。

Too much work.

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

Note that this will fail for numbers less than 1.

赠佳期 2024-12-18 09:06:49

@Ignacio Vazquez-Abrams 的答案提供了公式。但是,如果没有,那么您的代码作为不使用 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))

@Ignacio Vazquez-Abrams's answer provides the formula. But if there were none then your code as a loop without using sumYear2 could look like:

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

If you're not allowed to use sum (a homework) then:

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

For the second question assuming 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

If you are not allowed to use try/except then:

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)    

Where 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))

And 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))
清君侧 2024-12-18 09:06:49

你可以这样做

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

You can do this

>>> d=123456
>>> sum(int(c) for c in str(d))
21
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文