Using while loop as wait in python

I did this in C / C ++ until where I have a while loop that acts like an wait holding the program until the condition is violated. In Python, I try to do the same with while(GPIO.input(24) != 0): and it says it expects an indent. Is there a way to get the script to insert this statement until the condition is violated?

+6
source share
4 answers

In Python, you need to use the pass statement whenever you need an empty block.

 while (GPIO.input(24) != 0): pass 
+13
source

Note that an empty while loop will tend to freeze resources, so if you don't mind reducing the time resolution, you can enable the sleep statement:

 while (GPIO.input(24) != 0): time.sleep(0.1) 

This uses fewer CPU cycles, while still testing the condition at a reasonable frequency.

+13
source

Add pass , as such:

 while(GPIO.input(24) != 0): pass 

You may also consider a different approach:

 while True: if GPIO.input(24) == 0: break 

Which do you think is more readable.

+7
source

In python, you cannot leave the colon screw : so you must use pass to complete the empty block. Another way to use while this way

  while True: if GPIO.input(24) == 0: break 
+3
source

Source: https://habr.com/ru/post/945709/


All Articles