Home > Net >  Problem with local variable. NameError: name 'b' is not defined in python
Problem with local variable. NameError: name 'b' is not defined in python

Time:04-06

There is something wrong with my code. I still don't understand how local variable works. The following is an example of a simple code. And I have a NameError issue. Why? How can I fix this? I need to fix this error without Global variables! And there must be variable(a) ! What should I do for the answer of this code to come out 21?

def first(a):
    a = 0
    b = 3
    return b
def second(a):
    a = 0
    j = 7
    return j
def result():
    return first(b) * second(j) # <-NameError: name 'b' is not defined in python 
print(result())

CodePudding user response:

You should define what does your b and j mean in string 10: For python you are giving noting to function, but this function is asking for some value (a), it should be like this:

def first(a):
    a = 0
    b = 3
    return b
def second(a):
    a = 0
    j = 7
    return j
def result():
    b = 123 # Difining what are we giving to our functions
    j = 5

    return first(b) * second(j) # Now it will work
print(result())

So you can use b and j value, and access return values:

    b = 3
    return b

    j = 7
    return j

Think like this, when you're returning some value, it fully replaces function with that value.

CodePudding user response:

Here, b is only defined within the scope of function first()

This means that any code outside of this function cannot access that variable.

Unless the variable is marked as global b it will only be accessible within that 'block' of code

Example:

# Variable not defined in a function, therefore in global scope.
a = 10

def foo():
    # Variable defined in function, only accessible within function
    b = 10

    # NOT RECCOMENDED
    # Variable marked as global and accessible anywhere after assignment
    global c
    c = 10

    # Additional Note (Not important or useful)
    # Non local overrides local variables with a variable in an outer but not global scope
    d = 10    

    def bar():
        nonlocal d
        d = 20

print(a)  # 10 - No error, in global scope
print(b)  # Error - b not in global scope
print(c)  # 10 - No error, in global scope

# nonlocal (ignore)
print(d)  # Error - d not in global scope

CodePudding user response:

Short answer: local variables can only be used inside the function where they are defined.

Let's look at your code to see what is going on:

def first(a):
    a = 0
    b = 3.      # b is defined inside of `first()`
    return b
def second(a):
    a = 0
    j = 7
    return j
def result():
    return first(b) * second(j) # trying to use `b` inside result() gives an error because there is no variable with that name defined here. 
print(result())

See the comments on the relevant lines. I don't know what you are trying to do here, so I can't give any suggestions about how to fix it.

  • Related