2017-04-14 51 views
-1

我一直在試圖編寫一個程序,它可以找到輸入數學函數的根。我剛剛開始,所以我在這裏展示的僅僅是開始,並且還有未使用的變量。與.join函數的陌生人錯誤

這裏我寫這應該更換期限與價值,你輸入,比方說,100以下的函數「X」的功能代碼:

code = list(input("Enter mathematical function: ")) 
lowBound = int(input("Enter lower bound: ")) 
upBound = int(input("Enter upper bound: ")) 

def plugin(myList, value): 
    for i in range(len(myList)): 
    if myList[i] == 'x': 
     myList[i] = value #replaces x with the inputted value 
    return ''.join(myList) #supposed to turn the list of characters back into a string 

print(plugin(code,upBound)) 

但是當我運行該程序,我得到的錯誤:

Traceback (most recent call last): 
File "python", line 11, in <module> 
File "python", line 9, in plugin 
TypeError: sequence item 0: expected str instance, int found 

(我使用的在線編程平臺,因此該文件就被稱爲「蟒蛇」)

這沒有任何意義,我。 myList不應該是一個int,即使它是正確的數據類型(str),它應該是一個列表。有人可以解釋這裏發生了什麼嗎?

+3

'upBound'是一個整數,你把它放到列表中。你不能使用'str.join()'來加入字符串值以外的任何東西。 –

回答

1

您正在用int類型替換str類型(或字符)。

試試這個:

myList[i] = str(value) 
0

只能加入串

return ''.join(str(x) for x in myList) 

或者,更簡潔的迭代。刪除功能

print(''.join(str(upBound if x =='x' else x) for x in code)