【问题标题】:Using for loop to add 10 numbers使用for循环添加10个数字
【发布时间】:2017-07-14 19:23:53
【问题描述】:

编写一个程序,询问用户 10 个数字并打印出总数。在 for 循环的帮助下,我需要收集 10 个值并添加它们。如下例所示:

这是程序的示例运行:

Please enter a number: 5
Please enter a number: 2015
Please enter a number: -100
Please enter a number: 3
Please enter a number: -999
Please enter a number: 8
Please enter a number: 67
Please enter a number: 19
Please enter a number: 17
Please enter a number: -1234

The total is -199       
=========================================

以下是我迄今为止尝试过的。但是,我不确定如何将 for 循环收集的所有值相加,因为变量 num 仅保留循环中的最后一个值

def main():
    for n in range(10):
        num=eval(input("number?"))
        total=num
        print(total)

main()

【问题讨论】:

  • SO 不是代码编写服务。请展示你迄今为止的努力。
  • 我了解 SO 不是代码编写服务。如果能提供建议,将不胜感激。以下是我到目前为止所尝试的: def main(): for n in range(10): num=eval(input("number?")) total=num print(total) main()

标签: python loops for-loop


【解决方案1】:

前面的回答确实报错了:

UnboundLocalError Traceback(最近一次调用最后一次) 在 () 8 9 ---> 10 main()

在 main() 2 对于范围内的 n (10): 3 num =int(input("请输入一个数字:")) ----> 总共 4 个 += 数量 5 6 print("总数为" + 总数)

UnboundLocalError: 赋值前引用了局部变量“total”

这可以通过以下方式轻松解决:

def main():
    total = 0
    for n in range(10):
        num =int(input("Please enter a number: "))
        total += num

    print("The total is ", total)
    print("=========================================")

或者我是如何解决最初的问题的:

def add(itr):
  total = 0
  for n in range(itr):
    num = float(input("number:"))
    total+= num
    print(total)
add(10)

【讨论】:

    【解决方案2】:

    你所拥有的非常接近。您希望每次将total 增加num。您还想使用int() 函数将输入转换为整数。此外,您希望总数在最后只打印一次,因此它应该在循环之外。

    def main():
        for n in range(10):
            num =int(input("Please enter a number: "))
            total += num
    
        print("The total is " + total)
        print("=========================================")
    
    
    main()
    

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多