0

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

2
  • random.choices returns a list. x isn't equal to any of the strings in traveller_gen, because it's a list, not a string. Commented May 15, 2021 at 20:49
  • thanks for the help. i'll work on the variable names. Commented May 16, 2021 at 6:40

1 Answer 1

1

random.choices returns a list. So weather_gen returns a list. x isn't equal to any of the strings in traveller_gen, because it's a list, not a string.

If you still want to use random.choices but want weather_gen to return a string, not a list, you could change return x to return x[0].

By the way, I'm sure you can come up with more descriptive variable names than x and y.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.