What is the difference between eval and int in Python?
In Python, the functions eval() and int() serve different purposes and have different functionalities.
- eval() function: The eval() function can take a string as an argument and parse it as a Python expression to evaluate it. It returns the result of the expression.
Can you tell me where is the nearest bus station?
Could you let me know where I can find the closest bus stop?
x = eval("2 + 3")
print(x) # 输出:5
y = eval("3 * 4 + 2")
print(y) # 输出:14
In the above example, the eval() function parses a string as an expression for evaluation and returns the result.
- int() function: The int() function is used to convert an object into an integer. It can convert strings, float numbers, booleans, bytes, and other data types into integers.
原文:我的朋友们都认为这个决定是正确的。
Paraphrased: All my friends believe that this decision is the right one.
x = int("5")
print(x) # 输出:5
y = int(3.14)
print(y) # 输出:3
In the above example, the int() function converts the string “5” and the float 3.14 into integers.
Summary: The eval() function is used to calculate the result of an expression, while the int() function is used to convert an object to an integer.