C
Candace
Guest
Candace Asks: Is there a simpler way to see if a value is in a range of values and return a string?
This app works, but I was wondering if there is a better way to achieve this without the if/elif statements.
I am trying to improve the quality of my code in a Python app. Right now, I use a few if/elif statements to figure out if a value is in a range. If a value is in a certain range, my function returns a text string.
This app works, but I was wondering if there is a better way to achieve this without the if/elif statements.
Code:
def genre_function(weather_data):
weather_genre = ""
feelslike = int(weather_data\["weather"\]\["current"\]\["feelslike"\])
if feelslike \< 15:
weather_genre = "classical"
elif (
feelslike \>= 15
and feelslike \<= 45
):
weather_genre = "jazz"
elif (
feelslike > 44
and feelslike <= 70
):
weather_genre = "trip-hop,folk,chill,ambient"
elif (
feelslike > 70
and feelslike <= 79
):
weather_genre = "bossanova,soul"
elif (
feelslike > 79
and feelslike < 100
):
weather_genre = "synth-pop,indie-pop,soul"
elif feelslike < 99:
weather_genre = "electronic,dance,dancehall,disco,breakbeat"
return weather_genre
I am trying to improve the quality of my code in a Python app. Right now, I use a few if/elif statements to figure out if a value is in a range. If a value is in a certain range, my function returns a text string.