2013-12-23 24 views
1

我有以下代碼:的Python +可變

#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 

我試圖尋找「爲我在「+」變量「,和其他種類,但找不到任何東西...

我有兩個問題:

  1. 你會建議我搜索什麼?

  2. 我該如何解決這個問題,以便我可以查找任意數字的兩個倍數之和?

任何幫助將是偉大的。

回答

3

你可能想這樣的:

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

謝謝。這確實奏效! –

1

在Python中,使用一系列值的for循環迴路。這些可以是,例如,列表中的項目;或者這些可以是來自「迭代器」的值。

for i in 3在Python中沒有意義,因爲3不是一系列值。

要循環一系列整數,請使用range()xrange()

How does the Python's range function work?

+0

感謝您的信息! –

+0

感謝您提供什麼樣的建議。似乎認爲這是挑戰的一半。 –

0

下面是Python的for語法的文檔: http://docs.python.org/2/reference/compound_stmts.html#for

它值的任何序列,而不僅僅是像其他語言的數字序列遍歷。

玩得開心學習Python,它是一門很棒的語言。另外,歐拉工程項目的挑戰很有趣,所以堅持下去,不要放棄!

+0

謝謝!挑戰很有趣。 –