unboundlocalerror problem: local variable 'num' referenced before assignment

Asked

Viewed 16,086 times

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 make a function that has a 0 or 1 final result, depending on the random number that was created, but I can’t finish because of this error. how to proceed?

2 answers

2


The problem is the variable scope num.

It is declared within the if scope:

if semente != None:
    num=semente

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

num_aleatorio = (num*a+b)%m

Will give error because for function scope fnum_aleatorio the variable num does not exist. It exists only 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 for None.

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

Then I’d be:

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
  • thanks for the help! but not yet managed, it seems that it only provides me a number, whenever I run the program, it gives the same result.

0

In your code you only start the variable num if the semente is different from None, if semente for equal to 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 preference), 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
  • thanks for the help! but not yet managed, it seems that it only provides me a number, whenever I run the program, it gives the same result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.