# Regular expression that checks for valid characters in an expression
valid_chars='[ 0-9.\(\)+-\/*]'
valid_chars='[ 0-9a-z.\(\)+-\/*=]'
variables={}
defprint_error(error_code):
@ -24,6 +26,8 @@ def print_error(error_code):
print("You have two operators next to each other.")
case4:
print("One of your values is improperly formatted.")
case5:
print("Uninitialized variable.")
defcheck_errors(expr):
expr_small=expr.replace("","")# Remove spaces from the string, to make it easier to parse
@ -54,9 +58,10 @@ def check_errors(expr):
expr=parse(expr)
forvalinexpr:
ifval.count('.')>1:
ifval.count('.')>1:# A value can have at most 1 period
return4
ifval.isalpha()andnotvalinvariablesandval!=expr[0]:# If the token is a string, and isn't in the dictionary, and isn't the variable at index 0 (e.g. 'x' in 'x = 4')
return5
return0
@ -66,6 +71,12 @@ def evaluate(subexpr): # Evaluate a tokenized expression, that contains no paran
print(subexpr)
forindex,valinenumerate(subexpr):# Replace variables with their values
ifstr(val).isalpha():
subexpr[index]=variables[val]
print(subexpr)
if(len(subexpr)==1):
returnfloat(subexpr[0])
@ -113,12 +124,28 @@ def find_inner(subexpr):
defmain():
whileTrue:
variable=''
expr=input()
errno=check_errors(expr)
iferrno!=0:
print_error(errno)
continue# If an error was generated, print an error message and continue on to the next iteration of the loop
expr=find_inner(expr)
expr_tokenized=parse(expr)
ifexpr_tokenized[0].isalpha()andexpr_tokenized[1]=='=':# If the expression assigns a value to a variable
variable=expr_tokenized[0]# The first token is the variable
expr_tokenized.pop(0)# Remove the first and second tokens