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")