NameError в Python с возвращаемой переменной из функции - PullRequest
0 голосов
/ 31 октября 2019

Функция FindACar работает на самом деле хорошо. Он делает то, что я хочу. Но есть только одна проблема, которая случается не очень часто, но иногда бывает. Я получаю ошибку: «NameError: имя randomchoice не определено». Я не понимаю почему. Я пытался сделать случайный выбор в качестве переменной golobal, но это не сработало.

Что не так с этим "случайным выбором" в моем коде?

Car_Auswahl = FindACar(bins,Price_List,Car_for_select)

def FindACar(bins,Price_List,Car_for_select):
    # global randomchoice
    choice_idx = [] #Initialisierung der Auswahl des Autos
    shape,scale = 4.2531, 7896.8 
    coeff = 1.1299564124727026  # = Car['Preis'].mean()/((ReadPreisList['avg']*ReadPreisList['Anzahl']).sum()/ReadPreisList['Anzahl'].sum())
    sample = np.random.gamma(shape, scale)*coeff 
    while sample < min(Price_List) :
        sample = np.random.gamma(shape, scale)*coeff    
    bin_idx = np.digitize(sample,bins) 
    if  0 < bin_idx < len(bins):
        for index, row in Car_for_select.iterrows():
            if bins[bin_idx-1] < row.Preis <= bins[bin_idx]:
                choice_idx.append(index) 
            else:
                pass
        if len(choice_idx) != 0:
            randomchoice = np.random.choice(choice_idx) 
    else:
        target = min(Price_List, key=lambda x:abs(x-sample)) 
        randomchoice = Price_List.index(target)
    return randomchoice
...