Table of Contents
This guide covers the eval ()() function in python. with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
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 TipsMake 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 vuongdef tinhChuvi(l):return 4*l# Dien tich hinh vuongdef tinhDientich(l):return l*1thucthi = 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 = 1N?u ?? dài b?ng 2 , Di?n tích = 2N?u ?? dài b?ng 3 , Di?n tích = 3N?u ?? dài b?ng 4 , Di?n tích = 4Nh?p hàm s? d?ng: tinhChuvi(l)N?u ?? dài b?ng 1 , Chu vi = 4N?u ?? dài b?ng 2 , Chu vi = 8N?u ?? dài b?ng 3 , Chu vi = 12N?u ?? dài b?ng 4 , Chu vi = 16Nh?p hàm s? d?ng: tinhdientichHà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.
Next, 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?cprint(eval('canbachai(9)', {'canbachai': sqrt, 'luythua': pow}))
The Case Transmits Both Global and Local Parameters
from math import *a = 5print(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
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.