Search code examples
pythonwhile-loopraspberry-pi-zerogpiozeropendulum

Nested while patterns in Python


I'm a Python beginner trying to write a script for a Raspberry Pi Zero.

The idea is to turn the lights on at dawn and off at dusk, keeping in mind those times change every day. So what i'm after (i guess) is something that will run 24/7 and evaluate whether lights should be on or off.

Here is what I have so far, which doesn't work. Can you guys tell me where I've gone wrong ?
I would be very grateful

#!/usr/bin/python

import pendulum
from time import sleep
from gpiozero import LED, PWMLED
from astral import LocationInfo
from astral.sun import dusk, dawn, midnight

now      = pendulum.now('Europe/Paris')
tomorrow = pendulum.tomorrow('Europe/Paris')
home     = LocationInfo("Mons-en-Baroeul", "France", "Europe/Paris", 50.6, 3.1)
dawn     = dawn(home.observer)
dusk     = dusk(home.observer)
midnight = midnight(home.observer)
blue     = LED(23)
red      = LED(24)

def lights_on():
  blue.on()
  red.on()

def lights_off():
  blue.off()
  red.off()

while True:
  while dawn <= now < dusk:
      lights_on()
      if now >= dusk:
        break
  while dusk <= now:
      lights_off()
      if now >= midnight:
        break
  else:
      lights_off()

Solution

  • You need to update now inside the loop Also the logic is much more simple

    Here's a proposal of the fixed code:

    #!/usr/bin/python
    
    import pendulum
    from time import sleep
    from gpiozero import LED, PWMLED
    from astral import LocationInfo
    from astral.sun import dusk, dawn, midnight
    
    now      = pendulum.now('Europe/Paris')
    tomorrow = pendulum.tomorrow('Europe/Paris')
    home     = LocationInfo("Mons-en-Baroeul", "France", "Europe/Paris", 50.6, 3.1)
    dawn     = dawn(home.observer)
    dusk     = dusk(home.observer)
    midnight = midnight(home.observer)
    blue     = LED(23)
    red      = LED(24)
    
    def lights_on():
      blue.on()
      red.on()
    
    def lights_off():
      blue.off()
      red.off()
    
    while True:
      now = pendulum.now('Europe/Paris')
      if dawn <= now < dusk:
          lights_on()
      else:
          lights_off()