mercredi 10 février 2021

Toggling between two sets of boolean and string representations

I have 2 boolean variables:

a = True
b = True

and each one has some properties that manifests in their string representations:

a_str = "a is real"
b_str = "b is surreal"

And the results should:

  • Check if a and b is True, is so, output "a is real AND b is surreal"
  • Check if only a is True, then output: "a is real"
  • Check if only b is True, then output: "b is surreal"

I've tried the following and it works but eliciting the different if-elifs is rather verbose, i.e.

a = True
b = True

a_str = "a is real"
b_str = "b is surreal"

if a and b:
    print(f"{a_str} AND {b_str}")
elif a:
    print(a_str)
elif b:
    print(b_str)

esp. if there's a new variable c, e.g.

a = True
b = True
c = True

a_str = "a is real"
b_str = "b is surreal"
c_str = "c is cereal"

if a and b and c:
    print(f"{a_str} AND {b_str} AND {c_str")
elif a and b:
     print(f"{a_str} AND {b_str}")
elif a and c:
     print(f"{a_str} AND {b_str}")
elif b and c:
     print(f"{b_str} AND {c_str}")
elif a:
     print(a_str)
elif b:
     print(b_str)
elif c:
     print(c_str)

Is there a cleaner way to enumerate the different cases for the boolean checks?

Aucun commentaire:

Enregistrer un commentaire