2017-03-16 70 views
-3

的一個問題我一直在研究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 

我想知道爲什麼我收到此錯誤,以及如何解決它。

+3

什麼是你的問題? –

+0

您有具體問題嗎? – mdurant

+0

爲什麼我得到錯誤Traceback(最近一次調用最後): 文件「/home/echo/Mentos.py」,第46行,在 main() 文件「/home/echo/Mentos.py」,第17行,主 userinputvalue [x] + = 1 TypeError:列表索引必須是整數或切片,而不是str –

回答

0

Checks if x is a number

不,檢查x是否包含數字的字符串。

你想x.isdigit()

然後,

list indices must be integers or slices, not str

嘛,xstr,因爲這是input又回來了。

userinput = input("") # String 
for x in userinput: # characters, so still a string 

而且

Probally a better way to do this but meh

是的,有。

# A dictionary, not a list, you can't index an empty list 
    userinputvalue = {i : 0 for i in range(10)} 


    for x in userinput: 
     #Checks if x is a number 
     if x.isdigit(): 
      pass 
     elif x == ".": 
      pass 
     elif x in {'*','/','+','-'}: 
      pass 

,而且我用in因爲=>How do I test one variable against multiple values?

+0

這工作,我以前從未使用過字典,也許我應該看看他們。謝謝 –

+0

也稱爲其他語言的地圖或哈希 –

+0

這隻適用於數字,不適用於運營商。我 不知道你用'userinputvalue [「+」] + = 3'來完成什麼,例如 –