Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign operator to variable in python?

Usual method of applying mathematics to variables is

a * b 

Is it able to calculate and manipulate two operands like this?

a = input('enter a value') b = input('enter a value')  op = raw_input('enter a operand') 

Then how do i connect op and two variables a and b?
I know I can compare op to +, -, %, $ and then assign and compute....

But can i do something like a op b, how to tell compiler that op is an operator?

like image 990
Abhilash Muthuraj Avatar asked Jun 06 '10 04:06

Abhilash Muthuraj


People also ask

Can we assign operator to a variable?

You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b). Show activity on this post. It should be expression = a + c + b .

Which operators assign value to variable in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”.

How do you assign a command to a variable in Python?

In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.

How do you assign an operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.


1 Answers

You can use the operator module and a dictionary:

import operator ops = {     "+": operator.add,     "-": operator.sub,     "*": operator.mul,     "/": operator.div }    op_char = input('enter a operand') op_func = ops[op_char] result = op_func(a, b) 
like image 74
Matthew Flaschen Avatar answered Sep 20 '22 20:09

Matthew Flaschen