problem UnboundLocalError: local variable 'num' referenced before assignment

0
def fnum_aleatorio(a, b, m, semente=None):
    if semente != None:
        num=semente
    num_aleatorio = (num*a+b)%m  
    if num_aleatorio <= a//2:
        return 0
    else:
        return 1

I'm trying to do a function that has a final result of 0 or 1, depending on the random number that was created, but I can not finish because of that error. how to proceed?

    
asked by anonymous 24.03.2018 / 20:13

2 answers

0

The problem is the scope of the num variable.

It is declared inside the if statement:

if semente != None:
    num=semente

And you're trying to access it in the scope of the function:

num_aleatorio = (num*a+b)%m

It will give error because for the scope of the function fnum_aleatorio the variable num does not exist. It only exists within the scope of if .

One way to fix this is to do:

num = semente if semente is not None else 1 .

Where 1 is the default value of num when semente is None .

In this way you will be declaring the variable num within the scope of the function fnum_aleatorio .

So, I would stay:

def fnum_aleatorio(a, b, m, semente=None):
    num = semente if semente is not None else 1
    num_aleatorio = (num*a+b)%m  
    if num_aleatorio <= a//2:
        return 0
    else:
        return 1
    
24.03.2018 / 20:31
0

In your code you only start the variable num if the semente is different from None , if semente is equal a None the variable num will never be started, so there is no value in the variable to be used in the calculation in num_aleatorio = (num*a+b)%m , to solve this problem start the variable num with 0 (or any other value) outside the if (above preferably), see:

def fnum_aleatorio(a, b, m, semente=None):
    num = 0
    if semente != None:
        num=semente
    num_aleatorio = (num*a+b)%m  
    if num_aleatorio <= a//2:
        return 0
    else:
        return 1
    
24.03.2018 / 20:30