The eval () function in Python.
In this article, Quantrimang will continue to introduce you to a built-in function in Python, eval (). Eval () is an interesting utility that allows you to run Python code (this code is passed as parameters) right in the program.
In this article, Quantrimang will continue to introduce you to a built-in function in Python, eval (). Eval () is an interesting utility that allows you to run Python code (this code is passed as parameters) right in the program.
The syntax of eval () function in Python
eval(bieuthuc, global=None, local=None)
The parameters of the eval () function:
The eval () function has three parameters:
- bieuthuc: can be any valid Python expression
- global: a dictionary that specifies methods and global variables available.
- local: a dictionary specifies local methods and variables available.
Global and local use will be analyzed by Quantrimang later in this article.
Value returned from eval ()
Eval () returns results made from bieuthuc
Example 1: How does the eval () function work?
>>> eval("5 == 5")
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
Example 2: Using eval ()
# 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']
The case does not pass global and local parameters
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()'))
Where to pass global parameters and ignore local
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}))
The case transmits both global and local parameters
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
You should read it
- Max () function in Python
- The oct () function in Python
- The map () function in Python
- Sum () function in Python
- The ord () function in Python
- The function set () in Python
- The next () function in Python
- The function id () in Python
- Complex () function in Python
- The input () function in Python
- Min () function in Python
- The pow () function in Python
Maybe you are interested
How to Communicate Well With People from Other Cultures What does the 'super slow' 7680fps movie recording feature on the Mate 30 Pro do? Hitman Sniper famous game is being free on iOS and Android How to create slow motion videos on Android? 8 ways to win people's hearts 6 tips to help you get out of debt