【问题标题】:sum of even numbers within 1-100 using FOR LOOP [duplicate]使用 FOR LOOP 对 1-100 内的偶数求和 [重复]
【发布时间】:2020-07-17 23:21:05
【问题描述】:

我发现的代码都没有使用所要求的 for 循环,没有其他选项有效。

    total = 0 #defined total
    for number in range(1,101): #set a for loop with a range between (1-101)
        if number %2 == 0:  #if number(1-101) is divisible by 2 == 0
            total = sum(int(number)) #TypeError: 'int' object is not iterable
            print(total) # expected result is to print 2550

【问题讨论】:

  • FWIW,你甚至不需要循环来解决这个问题:sum(range(0, 101, 2))

标签: python python-3.x sum


【解决方案1】:

可以使用python内置函数sum。

sum(range(0, 101, 2))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多