I am using Skyfield API to calculate the phase in degree at a particular time. Phase in itself is meaningless and I want to name that phase which the degrees represent. 0° means New moon. 45° means waxing crescent.
moon_phases=['New Moon','Waxing Crescent', 'First Quarter','Waxing Gibbons','Full Moon','Waning Gibbons', 'Last Quarter', 'Waning Gibbons']
degrees=[0,45,90,135,180,225,270,315]
I want it to print New Moon even when the phase degree is 340° or 20°. What is the best approach for this? I don't want to use if else.
Solution:
A simple solution is to determine how many times 45 goes into your degrees.
import math
moon_phases=['New Moon','Waxing Crescent', 'First Quarter','Waxing Gibbons','Full Moon','Waning Gibbons', 'Last Quarter', 'Waning Gibbons']
degrees=[0,45,90,135,180,225,270,315]
degree = 177
i = round(degree / 45) % len(degrees)
moon_phase = moon_phases[i]
print(moon_phase)
>> Full Moon
Or you can just wrap this into a function, such as
def moon_phase(degree):
moon_phases=['New Moon','Waxing Crescent', 'First Quarter','Waxing Gibbons','Full Moon','Waning Gibbons', 'Last Quarter', 'Waning Gibbons']
degrees=[0,45,90,135,180,225,270,315]
i = round(degree / 45) % len(degrees)
moon_phase = moon_phases[i]
return moon_phase