我的翻译问题

时间:2017-03-16 17:24:59

标签: python python-3.x

过去几个小时我一直在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

我想知道为什么我会收到此错误以及如何修复它。

1 个答案:

答案 0 :(得分:0)

  

检查x是否为数字

不,检查x是否是包含数字的字符串。

您想要x.isdigit()

然后,

  

列表索引必须是整数或切片,而不是str

好吧,xstr,因为这是input返回的内容。

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

  

原来这是一个更好的方法,但是......

是的,有。

   # 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因为=&gt; How do I test one variable against multiple values?