我有一个计算器(Python 3.4.2),可以使用eval进行常规操作。
def calculator(user_input):
if any(c not in config.valid_cal_chars for c in user_input):
print("- Invalid Equation | Bad characters")
return
elif not any(c in user_input for c in "0123456789"):
print("- Invalid Equation | No numbers found")
return
sys.stdout.write("calculating " + "-".join(gfx.load_sequence))
time.sleep(0.1)
print (" | 100%")
try:
current_ans = eval(user_input)
except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
print ("- Invalid Equation | Error")
return
config.ans = current_ans
print (current_ans)
这里是config.py,config.ans和config.valid_cal_char都在引用它:
ans = ("0.0")
valid_cal_chars = ("0123456789-+/*ansqrt() \n")
如果您想知道什么是
user_choice
变量是指我在此函数之前拥有的输入函数。那部分已经起作用,所以不用担心。
但是,我想知道是否可能做到这样:
input equation here: 4*4 #this would be saved as the user_input variable
> 16 #the output of the equation
input equation here: sqrt(ans) #this would use the previous answer saved in config.ans (ans) and the sqrt() to find the square root of the previous printed value, so:
> 4
打“ans”将会得到:
input equation here: 1+1
> 2
input equation here: ans
> 2
使用sqrt()将会得到:
input equation here: 2+2
> 4
input equation here: sqrt(4)
> 2
如果你还不明白,sqrt() 函数会找到输入值的平方根。ans 变量则是使用先前返回的值。因此,将这两个组合在一起 "sqrt(ans)" 将给出先前返回值的平方根。
背景知识介绍完毕,我想让用户在计算时使用这些函数。虽然 "eval" 可能不起作用,但我很乐意使用 "exec"(了解其中的危险)。然而,这是一个 multitool.py 的主文件,它导入了这个文件 (functions.py) 来使用我在里面所有的函数,包括这个。
import os, sys, glob, math, random, login, gfx, config, functions, time
path = "******" #creates path to folder (can be changed by commenting this line out and creating new one)
dirs = os.listdir( path ) #not used currently
functions.load_sequence_complete()
functions.username_login()
time.sleep(0.05)
functions.password_login()
print ("\n[credentials have been verified! proceeding to main program " + "-".join(gfx.load_sequence) + "]\n")
time.sleep(0.1)
program = True
while (program == True):
user_choice = functions.choice_selecter()
functions.validate_choice(user_choice)
如果您需要其他信息,请在评论或答案中提出,这样我就可以编辑此内容以帮助您帮助我 :)