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
this method unsafe, because having directly interpreted input (either eval or 2.6 "input") may lead malicious input "import os; <delete file>"code:what want do? 2+3 5
that's because you're thinking on procedural, switch gears functional, , can do: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
python 2.6
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:
#!/usr/bin/env python
# dictionary of tasks
tasks = {
"+" : lambda x, y: x + y,
"-" : lambda x, y: x - y,
"*" : lambda x, y: x * y,
"/" : lambda x, y: x / y
}
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](leftmost, rightmost)
# print result
print "%d %s %d = %d" % (leftmost, operator, rightmost, result)
will yield function addition, , executing in other function:php code:
f = tasks["+"]
all done in single line, anonymous functions.php code:
print f(2, 3) # prints 5
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk python var directly to evaluation
Ubuntu
Comments
Post a Comment