2015-10-23 25 views
1

我是一名初学者,使用Python 2.79进行编程。我正在编写一个程序“标记”一个数学公式,基本上将每个数字和运算符转换为列表中的一个项目。输入命令将输入​​视为int而不是Python中的str

我的问题是目前(因为它是一个语义错误,我还没有能够测试其余的代码呢)在我的输入命令。我要求用户输入一个数学公式。 Python将其解释为一个int。

我试图使它成为一个字符串,和Python基本解决了配方,并运行的解决方案通过我的记号化功能

我的代码如下:

#Turn a math formula into tokens 

def token(s): 
    #Strip out the white space 
    s.replace(' ', '') 
    token_list = [] 
    i = 0 
    #Create tokens 
    while i < len(s): 
     #tokenize the operators 
     if s[i] in '*/\^': 
      token_list.append(s[i]) 
     #Determine if operator of negation, and tokenize 
     elif s[i] in '+-': 
      if i > 0 and s[i - 1].isdigit() or s[i - 1] == ')': 
       token_list.append(s[i]) 
      else: 
       num = s[i] 
       i += 1 
       while i < len(s) and s[i].isdigit(): 
        num += s[i] 
        i += 1 
       token_list.append(num) 
     elif s[i].isdigit(): 
      num = '' 
      while i < len(s) and s[i].isdigit(): 
       num += s[i] 
       i += 1 
      token_list.append(num) 
     else: 
      return [] 
    return token_list 

def main(): 
    s = str(input('Enter a math equation: ')) 
    result = token(s) 
    print(result) 

main() 

任何帮助,将不胜感激

我期待到

+0

使用'raw_input'代替输入。输入很烂。 –

+0

在Python 2.x中,你必须使用'raw_input',而不是'input'。 – Barmar

+0

另外,'str.replace()'不能就地工作。做's = s.replace(...)'得到你想要的。 –

回答

1

Python将用户输入解释为整数的原因是因为行input('Enter a math equation: ')。 Python将其解释为eval(raw_input(prompt))raw_input函数根据用户输入创建一个字符串,并且eval评估该输入 - 因此5+2的输入被认为是"5+2"raw_input,而eval的结果是7

Documentation

相关问题