的一個問題我一直在研究python中一個簡單的數學解釋器,以提高我對編程語言作爲一個整體如何工作的理解。我的翻譯被稱爲Mentos(以JPod的書中的Ethan操作系統命名)。如果有任何寫得不好的代碼,我只是試圖讓這個工作起作用,優化將在以後進行。現在,這裏是我的代碼:最近幾個小時我的翻譯
#Defining my main vars
pointer = 0
intstartvalue = 0
intendvalue = 0
intpointer = 0
intlist = []
templist = []
def main():
#This code takes the user input
print("Mentos> ", end="")
userinput = input("")
userinputvalue = []
for x in userinput:
#Probally a better way to do this but meh
#Checks if x is a number
if x == ("1") or ("2") or ("3") or ("4") or ("5") or ("6") or ("7") or ("8") or ("9") or ("0"):
userinputvalue[x] += 1 #1 refers to an integer. I did intend to do this with a string in a list but it didn't work either
#Checks if x is a decimal point
elif x == ("."):
userinputvalue[x] += 2 #2 refers to a decimal point
#Checks if x is a operator
if x == ("*") or ("/") or ("+") or ("-"):
userinputvalue[x] += 3 #3 refers to a operator
#Will program this section when I can successfully store the input to memory
def add():
pass
def sub():
pass
def div():
pass
def mul():
pass
for c in userinputvalue:
if c == 1:
intstartvalue = c
#Great job me, embedded for loops
for x in userinputvalue:
if x == 3:
intendvalue = intendvalue - (c - 1)
intpointer = intstartvalue
#I intend to cycle through the input for numbers and and add it to a list, then join the list together
#To have the first number.
if __name__ == "__main__":
main()
當我編譯它,我得到的錯誤:
Traceback (most recent call last):
File "/home/echo/Mentos.py", line 46, in <module>
main()
File "/home/echo/Mentos.py", line 17, in main
userinputvalue[x] += 1
TypeError: list indices must be integers or slices, not str
我想知道爲什麼我收到此錯誤,以及如何解決它。
什麼是你的問題? –
您有具體問題嗎? – mdurant
爲什麼我得到錯誤Traceback(最近一次調用最後): 文件「/home/echo/Mentos.py」,第46行,在 main() 文件「/home/echo/Mentos.py」,第17行,主 userinputvalue [x] + = 1 TypeError:列表索引必須是整數或切片,而不是str –