Question

I am still learning python so please be nice :) I want to let the user to do something like this:

>> sqrt(4) #input
2 #output

and

>> sqrt(8) #input
2*rad(2) #if this is not possible, just say something like "not valid"

and

>> 4*4 #1st input
16 #1st output
>> sqrt(ans()) #2nd input
4 #2nd output

My code:

from math import sqrt
valid_chars = "0123456789-+/*ansqrt() \n"
while True:
    x = "x="
    y = input(" >> ")
    x += y
    def ans():
        try:
            return z
        except NameError:
            return 0
    if(y == "end" or y == "End" or y == "exit" or y == "Exit" or y == "cancel" or y == "Cancel"):
                        break
    if any(c not in valid_chars for c in y):
        print("WARNING: Invalid Equation")
        continue
    try:
        exec(x)
    except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
        print ("WARNING: Invalid Equation")
    if not(y == "()"):
        z = x
        print(x)
    else:
        print("WARNING: Invalid Equation")

And if the user inputs something like this:

>> sqrt()x
WARNING: Invalid Equation

I know that I have to change the valid_chars to this:

valid_chars = "0123456789-+/*ansqrt() \n"

or something. However, for the rest, I have almost no clue. Thank you in advance, if you have any questions or think that this is incomplete, please comment about it! :) Also, don't for get to answer :D

Update:

Some ideas:

Take the value inside or outside of the "()". Then make that value equal to for example "s". After that:

d = sqrt((int(s)))
print (d)

However, I need something that will exclude inputs that causes errors so the program does not crash.

Also, I am not making this public so the you can ignore the fact that taking python statement as input is a bad idea. However, I am interested in other ways on how to do the same thing as eval(). Thanks

Updated code:

Problem fixed:

                from math import sort
                valid_chars = "0123456789-+/*ansqrt() \n";
                while True:
                    x = "x="
                    y = input(" >> ")
                    x += y
                    def ans():
                        try:
                            return z
                        except NameError:
                            return 0
                    if(y == "end" or y == "End" or y == "exit" or y == "Exit" or y == "cancel" or y == "Cancel"):
                        break
                    if any(c not in valid_chars for c in y):
                        print("WARNING: Invalid Equation")
                        continue
                    try:
                        exec(x)
                    except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
                        print ("WARNING: Invalid Equation")
                    else:
                        if not(y == "()"):
                            z = x
                            print(x)
                        else:
                            print("WARNING: Invalid Equation")
Was it helpful?

Solution

I'm going to try an answer that does what you want although in a different way. By the way you shouldn't use 'eval()' normally but in this case i think it's the easiest way:

EDIT: eval() is evil and should not be used in general! However I am still suggesting this answer because the OP made it clear he will not make the code public and he is aware of the risks involved when evaluating user input.

import sys
from math import sqrt

while True:
  question = raw_input('Please input an equation: \n')
  if question == 'exit()':
    sys.exit('Bye')
  try:
    answer = eval(question)
    ans = answer
  except:
    print 'Invalid operation'
    continue
  print answer

Output (works in Python 2.7):

>>Please input an equation: 
>>sqrt(16)    
>>4.0
>>Please input an equation: 
>>sqrt(ans)
>>2.0
>>Please input an equation:
>>exit()
>>Bye
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top