问题
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:
What would you have suggested that I search for?
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