Python - use an operator at runtime

Is it possible to insert an operation (e.g *, +) between two variables at runtime? My solution without doing this is multiple if, elif statements, but I don't think that's the most efficient way to do it.

EDIT: What I meant is I get two integers, and I want to apply an operation on one of them with the other, e.g x * y, but I want to change * to another operator (maybe they're called functions? Not sure) e.g -, +,^ based on input.

Does that make sense? Basically think of it as a calculator.


I'm not sure if this is what you're looking for but the operator module has a lot of operations, e.g. add and mul (multiply):

import operator

var_1 = 2
var_2 = 3

print(operator.add(var_1, var_2))
print(operator.mul(var_1, var_2))

will print


Need Your Help

General behaviour of concatenation

perl concatenation system-calls

I am trying to run pdflatex as a system call from a Perl script.

How get Mercurial changes when I've already used hg clone?


Worked on my repo from work, and hg pushed the changes. Now in my home computer, how do I get the changes I saved from work considering I've already hg cloned the repo about two weeks ago but haven't

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.