Answers for "python eval"

3

python eval function

# eval(expression, [globals[, locals]]
x = 100 
y = 200 # x and y are global vars
eval('6 * 7')
# output : 42
eval('x + y')
#output : 300

# we can override global vars x and y as follows
eval('x + y',{'x':50,'y':25})
#output: 75 and not 300
     
'''eval accepts the following expression examples:
literals : 6 and 7 from above are literals also lists, floats, boolean,strings
names : my_num = 3 # the my_num is the name :NOTE that assignments are not allowed in eval
attributes: funtion_name.attribute
operations: * from above is an operator
functions: must return a value eval( sum( [8,16,32] ) ) gives: 56, fibonacci(3)
'''
Posted by: Guest on May-24-2021
1

eval in python

from math import *
names = {'square_root': sqrt, 'power': pow}
print(eval('dir()', names))

# Using square_root in Expression
print(eval('square_root(9)', names))
Posted by: Guest on July-10-2021
1

eval in python

expr="(2+(3*2))/2"
print(eval(expr))
Posted by: Guest on July-10-2021
0

eval in python

from math import *
print(eval('dir()'))
Posted by: Guest on July-10-2021
0

python eval

#Perfect if you want to store a mathematical expression without defining the
#variables used:
my_function = "5x**2 + 8x - 2"  #I want to define the function cleanly as a
                                #   variable
#insert definition of other varianles here
#insert other code here
def f(x):                       #Defining the function as the funtion f(x)                  
  return eval(my_function)    #Returning my_function with the x in f(x) as x

print(f(0))  #Printing f(0), thereby returning my_function with 0 as x
#Returns -2
Posted by: Guest on October-29-2021
0

eval in python

#string in another string
expr="'2+3'"
print(eval(expr))
print(eval(eval(expr)))
Posted by: Guest on July-10-2021

Python Answers by Framework

Browse Popular Code Answers by Language