-2

I need to do a conditional statement in Python with an operator (or, and) insert by the user. Example:

a = 1
b = 1
c = 1
operator = input("Type the operator: ")
if(a == b operator b == c):
    print("Yes")
else:
    print("No")

I know, I can do it using if inside if. But I wanna know other way to do it.

Henry Harutyunyan
  • 2,355
  • 1
  • 16
  • 22

2 Answers2

3

There is a library called operator!

import operator

ops = { "|": operator.or_, "&": operator.and_}

operator = input("Type the operator: ")

if(ops[operator](a == b, b == c):
    print("Yes")
else:
    print("No")

Lookup table idea is from this post.

Unfortunately, it does only work for bitwise operators. There are no and/or logical operators in the library.

banana
  • 349
  • 1
  • 3
  • 12
  • If you're curious why the logical `and` and `or` aren't there, [here's the answer](https://stackoverflow.com/a/7894752/10077). – Fred Larson Dec 20 '19 at 23:04
-1

You can use eval() function to do this.

a = 1
b = 1
c = 1
operator = input("Type the operator: ")
exp = f"a == b {operator} b == c"
if eval(exp):
    print("Yes")
else:
    print("No")