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

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

我的代码有问题。我仍然不明白局部变量是如何工作的。下面是一个简单代码的例子。我有一个 NameError 问题。为什么?我怎样才能解决这个问题?我需要在没有全局变量的情况下修复此错误!并且必须有 variable(a) !这个代码的答案出来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())

您应该定义字符串 10 中的 b 和 j 的含义: 对于python,你是在给函数赋值,但是这个函数要求的是某个值(a),它应该是这样的:

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())

因此您可以使用 b 和 j 值,并访问 return 值:

    b = 3
    return b

    j = 7
    return j

这样想,当您return输入某个值时,它会用该值完全替换函数。

这里,b只定义在函数first()

的范围内

这意味着此函数之外的任何代码都无法访问该变量。

除非变量被标记为 global b,否则它只能在 'block' 的代码

中访问

示例:

# 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

简答:局部变量只能在定义它们的函数内部使用。

让我们看看你的代码,看看发生了什么:

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())

查看相关行的评论。我不知道你想在这里做什么,所以我无法就如何修复它提供任何建议。