我正在研究Python编程:计算机科学导论(第二版)。在第二章的最后,练习之一是设计一个计算器。在此之前,他一直在使用eval()进行计算。我知道使用eval不利于安全性,但我不知道如何使用它。我可以现在就用,以后再担心,但我想养成好习惯。
我希望用户将他们想要的计算输入为一行,如下所示:
>>> input('Input your expression: ')
Input your expression: 4 * 5 / 2我已经看过这个帖子Pros and Cons on designing a calculator with eval了。答案给了他一个链接,显示了你如何绕过它。他的做法似乎很复杂,我不明白他是怎么做到的。
我想我需要eval()来解决这个问题。我的计算器代码在下面。谢谢你的帮助!
# Calculator.py
# This program will allow the user to input a mathematical expression (using python syntax)
# it will then evaluate the expression and print the result. It will unfortunately use eval
# but I dont know how to get around this problem. The program will loop to allow for
# multiple calculations.
expression = 'blank'
print('Calculator')
print(' ')
print('Welcome! Please input your desired expression, using python syntax.')
print('When you are finished, input end, and the program will finish.')
# Until the user inputs end, the calculator will continue to repeat.
while expression != 'end':
print('')
expression= input('Input your expression: ')
# Checks if the last digit of expression is a digit. I think this is fairly foolproof.
# I used last digit instead of first, bc a negative sign could have been in the first digit.
if expression[len(expression)-1].isdigit():
print('= ', eval(expression))
# A way to distinguish between 'end' and other strings. After this prints and loops back,
# program should end.
elif expression == 'end':
print('Shutting down... ')
# If the user inputs something where the last digit is not a digit, and is
# not end, the program will notify them and repeat.
else:
print('Enter with only digits and operators!')发布于 2018-07-27 04:59:00
eval可能就是你在这里想要的。eval主要是不受欢迎的,因为它允许应用程序的任何用户执行任意代码,这显然会导致安全漏洞。然而,既然你这样做是为了学习经验,而不是在公开发布的应用程序中,这并不是你真正关心的问题。特别是如果你只是在学习,我会暂时忽略这个,(绝对不要在生产应用程序中这么做)。
您需要执行:eval(input('please enter a expression')),它允许您执行任意表达式。
在链接的文章中,他们解释了eval需要另外两个可选参数,这些参数允许您限制哪个表达式可以由eval执行。
他将第二个参数设置为{"__builtins__":None},以限制您使用任何全局函数(如果将其设置为{},则像abs这样的内置函数仍然可用)。
他将第三个参数设置为他希望允许用户执行的所有函数的字典,因为他只是限制用户以前不能运行任何全局函数。
https://stackoverflow.com/questions/51550899
复制相似问题