在另一个函数中使用一个函数的返回结果

2024-04-27 00:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有几个问题,我读了,但我不能理解。我试图使用一个函数在另一个函数中返回的结果:

def multiplication(a):
    c = a*a
    return c

def subtraction(c):
    d = c - 2
    return d

print(subtraction(c))

输出:

NameError: name 'c' is not defined

我知道有可能使用全局变量,但我发现这不是一个好主意,因为变量可以改变它们的值。你知道吗

编辑:

这两个函数只是白痴的例子。我有两个带单词的函数,我需要在第二个函数中使用第一个函数的返回。在这个愚蠢的例子中,我需要第二个函数中第一个函数(c)的结果。你知道吗


Tags: 函数name编辑returnisdefnot例子
3条回答

那么为什么不使用返回值呢?你知道吗

print(subtraction(multiplication(24)))

什么?你知道吗

“c”不是在“减法”函数之外声明的。 您需要在打印前声明“c”。 假设你想让c等于5,那么:

c = 5
print(subtraction(c))

你没有正确调用你的函数。你知道吗

def multiplication(a):
    c = a*a
    return c

def subtraction(c):
    d = c - 2
    return d

# first store some value in a variable
a = 2

# then pass this variable to your multiplication function
# and store the return value
c = multiplication(a)

# then pass the returned value to your second function and print it
print(subtraction(c))

相关问题 更多 >