Im new to programming and I am trying to write two functions that generate between them a number that represents the number of travellers produced by a given population with a given weather. The two functions wotk on their own but when I try to get the first function (weather_gen) to feed its output into the second function (traveller_gen) I get the following error: UnboundLocalError: local variable 'y' referenced before assignment. However, I know that the return value x from the first function is in the second function because the print(x) command works. Its only when I ask the second function to return y that the problems arise.
import random
season = "summer"
p=100
def weather_gen(season):
weathers = ("snow", "rain", "drizzle", "sun", "gorgeous")
if season == "spring":
x = (random.choices(weathers, weights=(10,30,30,20,10), k=1))
if season == "summer":
x = (random.choices(weathers, weights=(0,10,10,50,30), k=1))
if season == "autumn":
x = (random.choices(weathers, weights=(5,20,25,35,10), k=1))
if season == "winter":
x = (random.choices(weathers, weights=(20,25,25,15,5), k=1))
return x
x = weather_gen(season)
def traveller_gen(x):
print(x)
if x == "snow":
t = random.randint(0, 10)
y = (t/100)*p
if x == "rain":
t = random.randint(40, 55)
y = (t/100)*p
if x == "drizzle":
t = random.randint(50, 75)
y = (t/100)*p
if x == "sun":
t = random.randint(85, 100)
y = (t/100)*p
if x == "gorgeous":
t = random.randint(100, 125)
y = (t/100)*p
return y
traveller_gen(x)
Have I missed something completely obvious? Best wishes, Saveric
random.choicesreturns a list.xisn't equal to any of the strings intraveller_gen, because it's a list, not a string.