name ' ' is not defined

Asked

Viewed 418 times

-1

def notas():
    opcao = 0
    while opcao != 5:
        n1 = int(input("Digite sua nota 1 :"))
        n2 = int(input("Digite sua nota 2 :"))
        n3 = int(input("Digite sua nota 3 :"))
        opcao = input("Deseja sair?")
        return opcao

def media():
    medias = (n1+n2+n3) / 3
    print(" Sua media é {}",media)

notas()
media()

I am a beginner in Python, and would like to know why is returning this error?

2 answers

2

You are returning the wrong variable, the right one would be to store the variables n1, N2, N3 within a list and return that list, and then pass this list as parameter in the second function.

def notas():
    opcao = 0
    # Aqui é criado a lista
    variaveis = []
    while opcao != 5:
        n1 = int(input("Digite sua nota 1 :"))
        n2 = int(input("Digite sua nota 2 :"))
        n3 = int(input("Digite sua nota 3 :"))
        variaveis.append(n1)
        variaveis.append(n2)
        variaveis.append(n3)
        opcao = input("Deseja sair? (Digite 5 para sair)")
    # Retornando a lista
    return variaveis

def media(variaveis):
    medias = (variaveis[0]+variaveis[1]+variaveis[2]) / 3
    print(f" Sua media é {medias}")

# Salvando o valor retornado
n = notas()
media(n)

0

Lucas, you’re returning the error of name ' ' is not defined, because the variables were not defined in the function media()

Note that you have defined the variables n1, n2, n3 and opcao in the body of function notas(), that is, they are with the local scope and therefore the function media() not the 'vision'

One way to solve this would be to define the variables as global:

def notas():
    global n1,n2,n3 
    opcao = 0
    while opcao != 5:
         n1 = int(input("Digite sua nota 1 :"))
         n2 = int(input("Digite sua nota 2 :"))
         n3 = int(input("Digite sua nota 3 :"))
         opcao = input("Deseja sair?")
         return opcao

def media():
    media = (n1+n2+n3) / 3
    print(" Sua media é {}",media)

notas()
media()

Note: I have not made any improvement in your code, but there is possibility to do several!

Because you are a beginner in Python, I advise you to study the following questions:

To understand what is Python scope:

How is a block of scope identified in a language like Python?

To understand the concept of global in Python:

Python functions-Global and local variables

What’s the difference between global and nonlocal in Python?

Browser other questions tagged

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