-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
49 lines (40 loc) · 1.6 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""MathREPL, a math expression evaluator using Python eval() and the math module."""
from mathrepl import PS1, USAGE, WELCOME
from mathrepl.evaluator import evaluate
def main():
"""Main loop: Read and evaluate user's input."""
print(WELCOME)
while True:
# Read user's input
try:
expression = input(f"{PS1} ")
except (KeyboardInterrupt, EOFError):
raise SystemExit()
# Handle special commands
if expression.lower() == "help":
print(USAGE)
continue
if expression.lower() in {"quit", "exit"}:
raise SystemExit()
# Evaluate the expression and handle errors
try:
result = evaluate(expression)
except SyntaxError:
# If the user enters an invalid expression
print("Invalid input expression syntax")
continue
except (NameError, ValueError) as err:
# If the user tries to use a name that isn't allowed
print(err)
continue
# Print the result if no error occurs
print(result)
if __name__ == "__main__":
main()