Added code to parse assignment expressions, and added error-checking for uninitialized variables

master
Aadhavan Srinivasan 1 year ago
parent 1caf8044ff
commit 1e28a6f756

@ -2,10 +2,12 @@ import re
from parse import *
# List of valid operators
opers = ['+', '-', '*', '/']
opers = ['+', '-', '*', '/', '=']
# Regular expression that checks for valid characters in an expression
valid_chars = '[ 0-9.\(\)+-\/*]'
valid_chars = '[ 0-9a-z.\(\)+-\/*=]'
variables = {}
def print_error(error_code):
@ -24,6 +26,8 @@ def print_error(error_code):
print("You have two operators next to each other.")
case 4:
print("One of your values is improperly formatted.")
case 5:
print("Uninitialized variable.")
def check_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)
for val in expr:
if val.count('.') > 1:
if val.count('.') > 1: # A value can have at most 1 period
return 4
if val.isalpha() and not val in variables and val != 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')
return 5
return 0
@ -66,6 +71,12 @@ def evaluate(subexpr): # Evaluate a tokenized expression, that contains no paran
print(subexpr)
for index, val in enumerate(subexpr): # Replace variables with their values
if str(val).isalpha():
subexpr[index] = variables[val]
print(subexpr)
if (len(subexpr) == 1):
return float(subexpr[0])
@ -113,12 +124,28 @@ def find_inner(subexpr):
def main():
while True:
variable = ''
expr = input()
errno = check_errors(expr)
if errno != 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_tokenized = parse(expr)
if expr_tokenized[0].isalpha() and expr_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
expr_tokenized.pop(0)
expr = find_inner(''.join(expr_tokenized))
variables.update({variable: expr})
else:
expr = find_inner(expr)
print(expr)
print(variables)
main()

Loading…
Cancel
Save