True
>>>
>>> eval("4 < 10")
True
>>>
>>> eval("8 + 4 - 2 * 3")
6
>>>
>>> eval("'py ' * 5")
'py py py py py '
>>>
>>> eval("10 ** 2")
100
>>>
>>> eval("'hello' + 'py'")
'hellopy'
Eval () not only performs simple expressions but can also execute functions, call methods, reference variables .
>>> eval("abs(-11)")
11
>>>
>>>
>>> eval('"hello".upper()')
'HELLO'
>>>
>>>
>>> import os
>>>
>>>
>>> eval('os.getcwd()') # hiển thị thư mục đang làm việc hiện tại
'/home/thepythonguru'
>>>
>>>
>>> x = 2
>>>
>>> eval("x+4")
6
# Viết bởi TipsMake.com
# Chu vi hinh vuong
def tinhChuvi(l):
return 4*l
# Dien tich hinh vuong
def tinhDientich(l):
return l*1
thucthi = input("Nhập hàm sử dụng: ")
for l in range(1, 5):
if (thucthi == 'tinhChuvi(l)'):
print("Nếu độ dài bằng ", l , ", Chu vi = ", eval(thucthi))
elif (thucthi == 'tinhDientich(l)'):
print("Nếu độ dài bằng ", l , ", Diện tích = ", eval(thucthi))
else:
print('Hàm không chính xác!')
break
Run the program, the result is:
Nhập hàm sử dụng: tinhDientich(l)
Nếu độ dài bằng 1 , Diện tích = 1
Nếu độ dài bằng 2 , Diện tích = 2
Nếu độ dài bằng 3 , Diện tích = 3
Nếu độ dài bằng 4 , Diện tích = 4
Nhập hàm sử dụng: tinhChuvi(l)
Nếu độ dài bằng 1 , Chu vi = 4
Nếu độ dài bằng 2 , Chu vi = 8
Nếu độ dài bằng 3 , Chu vi = 12
Nếu độ dài bằng 4 , Chu vi = 16
Nhập hàm sử dụng: tinhdientich
Hàm không chính xác!
You should be careful when using eval!
You need to pay a little attention if you are using a Unix system like macOS, Linux . and perform the functions of the os module. The os module is built to provide methods to help you create, delete, and change folders.
Then, if you enter the value as eval (input ()), the user may have problems changing the file even if it deletes the file with the os.system ('rm -rf *') command .
So, if you use eval (input ()) in your code, it is reasonable to check which variables and methods you can use. You should do this with the function dir ().
from math import *
print(eval('dir()'))
Running the code and the resulting result will look like this:
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp'
, 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma'
, 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh'
, 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
When using eval () without passing these two parameters as the examples above, the expression will be executed in the current scope. You can check the variables and methods available with dir () as mentioned above.
print(eval('dir()'))
Global and local (dictionary) parameters are used for global and local variables respectively. If dictionary local is ignored, this default program is in the global form . That is, global will be used for both global and local variables.
You can check local and global dictionary with global () and local () built-in functions ()
Example: Transfer an empty dictionary to the global parameter
from math import *
print(eval('dir()', {}))
# Code dưới đây sẽ xảy ra exception
# print(eval('sqrt(25)', {}))
If you pass a blank dictionary into the global , only the __builtins__ function is valid for bieuthuc. You will not be able to access any function of the math module even though the math module has been imported into the program above.
Run the program, the result is:
['__builtins__']
In this example, the expression can use the sqrt () and pow () functions together with __builtins__.
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
Alternatively, you can change the name of the available method for your desired expression.
from math import *
print(eval('dir()', {'canbachai': sqrt, 'luythua': pow}))
# dùng canbachai trong biểu thức
print(eval('canbachai(9)', {'canbachai': sqrt, 'luythua': pow}))
from math import *
a = 5
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))
Run the program, the result is returned
2.23606797749979
Previous article: enumerate () function in Python
Next lesson: float () function in Python