2

I want to receive operator (such as '+','-','*','/') and use it directly in the code body. someting like:

char = raw_input('enter your operator:')
a=1
b=5
c=a char b    #error! how can i do it?

If the user entered '*', c will be 5.

If the user entered '+', c will be 6 and so on..

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
Eliav Louski
  • 3,593
  • 2
  • 28
  • 52
  • No you can't create your own operators. https://stackoverflow.com/questions/932328/python-defining-my-own-operators – Saurav Sahu Oct 30 '18 at 03:21

4 Answers4

1

You could do something like this:

import operator

operations = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}

char = raw_input('enter your operator:')
a = 1
b = 5
c = operations[char](a, b)

print c

Output (for char = +)

6
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

Like this:

a=1
b=2
op = '+'
result = eval('{}{}{}'.format(a, op, b)) # result = 3

You'll have to translate a and b into strings as well for the eval to work.

Rocky Li
  • 5,641
  • 2
  • 17
  • 33
0

Or Use:

from operator import *
char = raw_input('enter your operator:')
a=1
b=5
c={'+':add,'-':sub,'*':mul,'/':truediv}
print(c[char](a,b))

Or int.some operator name:

char = raw_input('enter your operator:')
a=1
b=5
c={'+':int.__add__,'-':int.__sub__,'*':int.__mul__,'/':int.__truediv__}
print(c[char](a,b))

Demo Output for both cases:

enter your operator:*
5
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

This may be slower than using operators but I am including links that may be helpful and another approach using lambda that may help understand. Using the switch dict approach such as the others have used explained here I'm using lambda to coorelate the input into custom methods using this operators dict:

operators = {
    '-': lambda a, b: a-b,
    '+': lambda a, b: a+b,
    '/': lambda a, b: a/b,
    '*': lambda a, b: a/b)
char = raw_input('enter your operator:')
a=1
b=5
c=operations[char](a, b)
print(c)
Jab
  • 26,853
  • 21
  • 75
  • 114