Python eval() Function
The eval () Function of python can be used to evaluate and return the result of expression given as string.
for example
>> eval('8+9')
output
17
Similarly, following code fragment
y=eval("3*10")
print (y)
output
30
Since , eval() can interpret an expression given as string , you can use it with input() too.
example
var1=eval(input(enter value))
print(var1,type(var1))
output
enter value 9+8
17 <class 'int'>
See, the eval() not only interpreted the string ("15+3") as 18 but also stored the result as int value. thus
with eval (), if enter an integer or float value ,it will interpret the values as the intended type .
example
var1=eval(input(enter value))
print(var1,type(var1))
output
enter value 5+7
12 <class 'int'>
example
var1=eval(input(enter value))
print(var1,type(var1))
output
enter value 2.5+7
9.5 <class 'float'>
you can use eval() enter a list or also .Use [ ] to enter and ( ) to enter tuple values
example
var1=eval(input(enter value))
print(var1,type(var1))
output
enter value [1,2,3]
[1,2,3]<class 'list'>
No comments:
Post a Comment
for more information please share like comment and subscribe