Ad

How Do I Create A System With Limited If Statements?

- 1 answer

I'm trying to make a program where three levers control a security access system. The user is asked, for each lever, whether they pull the lever or not. In the end. if the second lever is pulled, the door will not open, but if either the first or third lever is pulled, then the door will open.

The caveat to this problem is that I'm limited to only one if statement and one else statement. I've racked my brains but cannot for the life of me think of a solution that encompasses all the situations with just two statements.

if __name__ == "__main__":
    door_one = str(input("Do you pull the first lever? "))
    door_two = str(input("Do you pull the second lever? "))
    door_three = str(input("Do you pull the third lever? "))
    if door_two == "yes":
        print("The door remains shut.")
    else:
        print("The door opens!")

Obviously this code is incorrect but I can't think of how I can reduce the number of statements to satisfy the conditions above

Ad

Answer

UPDATE

Maybe that's what you need to fill:

if __name__ == "__main__":
    door_one = str(input("Do you pull the first lever? "))
    door_two = str(input("Do you pull the second lever? "))
    door_three = str(input("Do you pull the third lever? "))
    if door_two == "yes" or (door_one != 'yes' and door_two != 'yes' and door_three != 'yes'):
        print("The door remains shut.")
    else:
        print("The door opens!")

another approach:

if __name__ == "__main__":
    levers = ['first', 'second', 'third']
    lever_vals = []
    for i in levers:
        lever_vals .append(str(input("Do you pull the %s lever? " % i)))
    if lever_vals[1] == 'yes' or all(i != 'yes' for i in lever_vals):
        print("The door remains shut.")
    else:
        print("The door opens!")
Ad
source: stackoverflow.com
Ad