【问题标题】:Python "for i in" + variablePython "for i in" + 变量
【发布时间】:2013-12-23 07:15:25
【问题描述】:

我有以下代码:

 #Euler Problem 1

    print "We are going to solve Project Euler's Problem #1"

    euler_number = input('What number do you want to sum up all the multiples?')
    a = input('Insert the 1st multiple here: ')
    b = input('Insert the 2nd multiple here: ')

    total = 0
    for i in euler_number:
        if i%a == 0 or i%b == 0:
    total += i
    print "Sum of all natural numbers below 'euler_number' that are multiples of 'a'"
    print "or 'b' is: ", total

出现以下错误:

Traceback (most recent call last):
  File "euler_1.py", line 10, in <module>
    for i in euler_number:
TypeError: 'int' object is not iterable

我尝试搜索“for i in”+“变量”等,但找不到任何东西......

我有两个问题:

  1. 你会建议我搜索什么?

  2. 如何解决这个问题,以便我可以找到任意数字的两个倍数之和?

任何帮助都会很棒。

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    你可能想要这个:

    for i in range(1, euler_number + 1):
    

    【讨论】:

      【解决方案2】:

      在 Python 中,for 循环使用一系列值进行循环。例如,这些可以是列表中的项目;或者这些可以是来自“迭代器”的值。

      for i in 3 在 Python 中没有意义,因为3 不是一系列值。

      要遍历一系列整数,请使用range()xrange()

      How does the Python's range function work?

      【讨论】:

      • 感谢您提供有关查找内容的建议。似乎认为这是挑战的一半。
      【解决方案3】:

      这里是 Python 的 for 语法的文档: http://docs.python.org/2/reference/compound_stmts.html#for

      它循环遍历任何值序列,而不仅仅是其他语言中的数字序列。

      祝您学习 Python 愉快,它是一门很棒的语言。此外,Project Euler 挑战很有趣,所以坚持下去,不要放弃!

      【讨论】:

      • 谢谢!挑战很有趣。
      猜你喜欢
      • 1970-01-01
      • 2011-07-27
      • 2016-03-12
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多