我是一名使用 Python 2.79 编程的初学者。我正在编写一个程序,“标记”一个数学公式,基本上将每个数字和运算符转换为列表中的一个项目。
我的问题目前在我的输入命令中(因为这是一个语义错误,我还无法测试其余的代码)。我要求用户输入一个数学方程。 Python 将此解释为 int。
我尝试将它变成一个字符串,Python 基本上解决了这个公式,并通过我的 tokenize 函数运行了解决方案
我的代码如下:
#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()
如有任何帮助,我们将不胜感激
我正在寻找
最佳答案
Python 将用户的输入解释为整数的原因是 input('Enter a mathequation: ')
行。 Python 将其解释为 eval(raw_input(prompt))
。 raw_input
函数根据用户输入创建一个字符串,并且 eval
评估该输入 - 因此 5+2
的输入被视为 “5+2”
by raw_input
,eval
将其计算为 7
。
关于python - 输入命令将输入作为 int 而不是 Python 中的 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33306145/