Python “for i in” + variable

一世执手 提交于 2021-02-05 08:45:34

问题


I have the following code:

 #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

With the following error:

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

I tried to search for "for i in" + "variable", and other sorts, but could not find anything...

I have two questions:

  1. What would you have suggested that I search for?

  2. How can I solve this so that I can look for the sum of two multiples for any number?

Any help would be great.


回答1:


You probably want this:

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



回答2:


In Python, a for loop loops using a series of values. These can be, for example, items in a list; or these can be values that come from an "iterator".

for i in 3 makes no sense in Python, as 3 is not a series of values.

To loop over a series of integers, use range() or xrange().

How does the Python's range function work?




回答3:


Here's the documentation for Python's for syntax: http://docs.python.org/2/reference/compound_stmts.html#for

It loops over any sequence of values, not just a sequence of numbers like in other languages.

Have fun learning Python, it's a great language. Also, the Project Euler challenges are fun, so stick with them, and don't give up!



来源:https://stackoverflow.com/questions/20738692/python-for-i-in-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!