Error in python3 function

Asked

Viewed 50 times

1

I made this function where will be assigned a name and a value, which enter a while loop repeating 5 times, each time the loop repeats the values will be assigned to a different list, finally it calculates the average of the values of each list and returns it, but I’m making a mistake and I can’t solve it.

ERROR:line 20, in media_ms media = (dic0[name] + dic1[name] + dic2[name] + dic3[name] + dic4[name]) / 5 Unboundlocalerror: local variable 'dic4' referenced before assignment.

def media_ms(site_nome, site_ms):
    nome = str(site_nome)
    ms = float(site_ms)
    y = 0
    while y < 4:
        if y == 0:
            dic0 = {nome: ms}
        elif y == 1:
            dic1 = {nome: ms}
        elif y == 2:
            dic2 = {nome: ms}
        elif y == 3:
            dic3 = {nome: ms}
        elif y == 4:
            dic4 = {nome: ms}

        y += 1

    if y==4:
        media = (dic0[nome] + dic1[nome] + dic2[nome] + dic3[nome] + dic4[nome]) / 5

    return media

t = media_ms('google.com', 40)
print(t)

2 answers

0

Your code never enters

elif y == 4:

, for his while is <4 and not <=4...

That way, he doesn’t create his dic4, therefore the error" local variable 'dic4' referenced before assignmen".

Adjust your while or else install your variable dic4 as empty at the beginning of the code: dic4 = {}

  • Thanks buddy, it worked.

0

def media_ms(site_nome, site_ms):
    nome = str(site_nome)
    ms = float(site_ms)
    y = 0
    while y <= 4:
        if y == 0:
            dic0 = {nome: ms}
        elif y == 1:
            dic1 = {nome: ms}
        elif y == 2:
            dic2 = {nome: ms}
        elif y == 3:
            dic3 = {nome: ms}
        elif y == 4:
            dic4 = {nome: ms}
        y += 1

    if y == 5:
        media = (dic0[nome] + dic1[nome] + dic2[nome] + dic3[nome] + dic4[nome]) / 5

    return media

t = media_ms('google.com', '40')
print(t)

There’s your code working, what I changed was:

no while, for the loop to reach the end, I changed the 'y < 4' comparator by 'y <= 4'

and changed the end if value from 4 to 5.

Your error was happening because the final if was not being accessed, and Voce returned a variable that had not been instantiated.

I hope to have helped, any doubt can inform me

Browser other questions tagged

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