Created
February 1, 2012 12:16
-
-
Save quandyfactory/1716786 to your computer and use it in GitHub Desktop.
A silly little script that evaluates command line mathematical expressions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""A silly little script that evaluates command line mathematical expressions.""" | |
from __future__ import division | |
import sys | |
if __name__ == '__main__': | |
expression = ' '.join(sys.argv[1:]) | |
if len(expression) == 0: | |
sys.exit(""" | |
Enter a mathematical expression as the command line argument for this script. | |
Examples: | |
python calc.py 2 + 5 | |
python calc.py 2 ** 5 | |
python calc.py 5 * (3 + 2) | |
python calc.py 5 / 2 | |
Note: by default, this script performs floating point division. | |
For integer division, use a double-slash - // - instead of a single slash - / - in your expression.""") | |
validchars = '0123456789 +-*/()=.' | |
valid_expression = ''.join([c for c in expression if c in validchars]) | |
if valid_expression != expression: | |
sys.exit('\nSorry, but "%s" is not a valid mathematical expression.' % (expression)) | |
print '\n%s = %s' % (valid_expression, eval(valid_expression)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment