while not error-how to make an alternative

62 Views Asked by At

This is the current code:

def wait_for_button(button):
    while not (button.read()) :
        pass
wait_for_button(push_button1)
print('Hi')
wait_for_button(push_button2)
print('Bye')

But the problem with this code is that push_button1 has to be pressed first, and, only then, will the push button 2 work. If push button 1 is not pressed before push button 2, it will not print out 'Bye' (referring to the code above).

Is there a way such that instead of going in a sequence (pushputton1->pushbutton2) ,it can go either way, i.e. no matter which button is pressed first, the code will still work? Thanks

2

There are 2 best solutions below

2
David Duran On BEST ANSWER

If I understand correctly the question, you want to exit when button 2 is pressed (regardless whether button 1 has been pressed). You could create the following function for such a case:

def wait_for_buttons(button1, button2):
    button1_pressed = False
    button2_pressed = False

    while not button2_pressed:
        if button1.read():
            button1_pressed = True
            print("Hi")
        if button2.read():
            button2_pressed = True

wait_for_buttons(push_button1, push_button2)
print('Bye')
0
TheAnswerIs42 On

If I understand correctly and you want to check if both buttons are pressed and only then print 'Bye'. You can create a 2 boolean variables for button 1 and 2, then if both variables are set to true, print. Something like this:

def wait_for_button(button1,button2):
    button_pressed1=False
    button_pressed2=False

    print ("Hi")
    while not button_pressed1 and not button_pressed2:
        if button1.read():
            button_pressed1=True
        if button2.read():
            button_pressed2=True
    print ("Bye")

This way it doesn't matter which button is pressed first, once both has been pressed in any order, the while loop ends and the function prints "Bye".