Lesson Three: Conditional Logic
Right now we are essentially showing the hours in "military time," using a whole number between 0 and 23. Some people would rather use the AM/PM indicator instead, using whole numbers between 1 and 12 then lighting an LED up to indicate if the time relates to the evening hours or the morning hours.
Essentially we want to tell our clock that if the "hours" variable is less than 12, we need to keep the evening indicator light off. If the variable is greater than or equal to 12, we need to light the evening indicator. This kind of either/or logic is considered "conditional logic" when programming.
Python, like a lot of languages, uses the keywords "if" and "else" to indicate if something is true, execute some code, else execute a different section of code. You can expand this logic to do something if a variable or condition is not true as well.
With this lesson we will change our code from Lesson 2 only slightly, introducing a new variable called "is_evening" that is True if the hours are greater than 12.
We now have created our own variable that knows if it is current the evening or not. If we are not in the evening, we assume we are currently in the morning hours. Right after we define the variable "now," let's define "is_evening:"
# Show the current time def showCurrentTime(): now = datetime.now() # Set the hours is_evening = now.hour > 12
Now let's use this new knowledge to tell the clock to display the current hour if it is not the evening, else subtract twelve hours from the current hour.
# Show the current time def showCurrentTime(): now = datetime.now() # Set the hours is_evening = now.hour > 12 display.setHours(now.hour if not is_evening else now.hour - 12)
Now we no longer show things in military time! We still need a way to indicate if it's the morning or the evening however. Luckily this is easy - we don't even need to use conditional logic!
# Show the current time def showCurrentTime(): now = datetime.now() # Set the hours is_evening = now.hour > 12 display.setHours(now.hour if not is_evening else now.hour - 12) # Set the indicator lights display.setColon(True) display.setEvening(is_evening)
Essentially what we are doing here is saying the evening indicator should be the same value as "is_evening," which is always either True or False. If "is_evening" is true, "setEvening()" is true as well!
We have now covered functions, variables, constructors and conditional logic. Those concepts will carry us through to our next lesson: playing our music in the morning!