Kofi 611
Kofi 611

Reputation: 33

Is there a way to shorten this if statement?

I am trying to make it so that if two or more variables are False, then the statement ends; but the way I'm doing it, the code is taking up way too much space.

if g == False and h == False:
  print("Use a different formula.")
  return
elif g == False and i == False:
  print("Use a different formula.")
  return
elif g == False and c == False:
  print("Use a different formula.")
  return
elif h == False and i == False:
  print("Use a different formula.")
  return
elif h == False and c == False:
  print("Use a different formula.")
  return
elif i == False and c == False:
  print("Use a different formula.")
  return
elif g == False and h == False and i == False:
  print("Use a different formula.")
  return
elif g == False and h == False and c == False:
  print("Use a different formula.")
  return
elif h == False and i == False and c == False:
  print("Use a different formula.")
  return
elif c == False and i == False and g == False:
  print("Use a different formula.")
  return
elif g == False and h == False and i == False and c == False:
  print("Use a different formula.")
  return

This is what I have and it technically should work, but there has to be a way to shorten this. Please help.

Upvotes: 3

Views: 58

Answers (1)

kaya3
kaya3

Reputation: 51037

Python's Boolean values True and False can be treated arithmetically as the integers 1 and 0 respectively. So if you add them together and the result is less than or equal to 2, then at least two must be false.

if g + h + c + i <= 2:
    ...

As @MadPhysicist notes in the comments, this works because bool is a subclass of int.

Upvotes: 9

Related Questions