0

Here's what i am trying to do. I am basically having a truth-table for two boolean formulas:

x=[True, False]
y=[True, False]
a=[]
for i in x:
    for z in y:
        a.append([i, z])

Now I want to input some boolean expression and check it in every "row" of my truth-table. I tried this:

p=None
q=None
result=[]
exp=input("Type your boolean expression using p and q as variables: ")
for i in a:
    p, q = i[0], i[1]
    result.append(exp)
    print(result)

But when I try to type some boolean expression as input, for example:

 (not p) or q

It uses at as a string. But if I do this:

exp=bool(input("Type your boolean expression using p and q as variables: "))

then every non-empty string would be regarded as True in bool. How can I solve this?

  • 1
    you can use `eval(exp)` before the for loop. it might do the trick but is generally not suggested to use eval(). – Amit Kumar Nov 14 '20 at 14:32

1 Answers1

0

From what you said I understand that you want to apply a hand written expression to all elements of a list.

If your table is always 2-element wide you can go with :

table = [[True, True], [False, True], [True, False]]  
expression  = 'p and q'  
[eval(expression) for p, q in table]  
# Output
[True, False, False]

However your expression need to respect Python syntax. What's more eval is slow. So this answer can probably be enhanced.

More information about eval here : Documentation

Remi
  • 26
  • 3
  • Related to the use of eval: https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice – jarmod Jan 08 '21 at 15:43