Skip to main content

Thread: python var directly to evaluation


is possible have python take math symbol entered variable , put directly operation, ex

x = input('enter operator')
y = input('enter 1st #: ')
z = input('enter second #: ')

want print out result. can do
y _ z

can manually make bunch of 'if' statements , fill in appropriate operation in underlined blank.. however, there lots of operations check for. there equivalent doing

print y x z

there python plugs in , sees expression, , evaluates it?

the easiest way, eval, in fact, you're allowing use expressions in input because of function "input"

python 2.6
"raw_input" : reads input string
"input" : reads input python expression

(will deprecated in favor of)
python 3.x
"input" : reads input string.

see yourself:
php code:
evalme input("what you want to do?")

print 
evalme 
code:
what want do? 2+3   5
this method unsafe, because having directly interpreted input (either eval or 2.6 "input") may lead malicious input "import os; <delete file>"

i can manually make bunch of 'if' statements , fill in appropriate operation in underlined blank.. however, there lots of operations check for. there equivalent doing
that's because you're thinking on procedural, switch gears functional, , can do:

python 2.6
php code:
#!/usr/bin/env python

# dictionary of tasks
tasks = {
    
"+" lambda xyy,
    
"-" lambda xyy,
    
"*" lambda xyy,
    
"/" lambda xyy
}

operator raw_input("enter an operator >").strip()
leftmost int(raw_input("enter the left-most oparand >"))
rightmost int(raw_input("enter the right-most oparand >"))

# call the function on the dictionary
# with both arguments
result tasks[operator](leftmostrightmost)

# print result
print "%d %s %d = %d" % (leftmostoperatorrightmostresult
the reason why works, because dictionary, works getting key (the operator in case) , returning it's value (a function in case). therefor, calling:

php code:
tasks["+"
will yield function addition, , executing in other function:

php code:
print f(23# prints 5 
all done in single line, anonymous functions.


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk python var directly to evaluation


Ubuntu

Comments

Popular posts from this blog

opencv3, tbb and rasp pi 2 - Raspberry Pi Forums

small ethernet problem - Raspberry Pi Forums

Multithumb configuration params not working? - Joomla! Forum - community, help and support