Reputation: 125
I am a beginner programing with Python 2.79. I am writing a program that "tokenizes" a mathematical formula, basically turning each number and operator into an item in a list.
My problem is currently (because it is a semantic error i haven't been able to test the rest of the code yet) in my input command. I am asking the user to enter a mathematical equation. Python is interpreting this as an int.
I tried making it into a string, and Python basically solved the formula, and ran the solution through my tokenize function
My code is as follows:
#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()
Any help would be appreciated
I am looking to
Upvotes: 1
Views: 109
Reputation: 656
The reason Python is interpreting the user's input as an integer is because of the line input('Enter a math equation: ')
. Python interprets that as eval(raw_input(prompt))
. The raw_input
function creates a string from the user input, and eval
evaluates that input -- so an input of 5+2
is considered "5+2"
by raw_input
, and eval
evaluates that to be 7
.
Upvotes: 1