Python归来的烦恼

2024-09-30 02:27:10 发布

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

有人能解释一下我做错了什么吗

我的代码显示为x not defined。我要做的是在add1中得到x的结果,并将其传递给doub函数。我已经尽可能多地搜索和阅读了这篇文章,我知道我遗漏了一些东西,所以请给我指出正确的方向

def main():
    value = (int)(input('Enter a number '))
    add1(value)
    doub(x)

def add1(value):
    x = value + 1
    return x


def doub (x):
    return x*2

main()

Tags: 函数代码inputreturnvaluemaindefnot
2条回答

试试这个:

def main():
    value = int(input('Enter a number '))
    #This is more pythonic; use the int() function instead of (int)         
    doub(add1(value))

def add1(value):
    x = value + 1
    return x


def doub (x):
    return x*2

main()

x只存在于add1函数中。您的main函数只知道调用add1返回的,而不是它以前存储的变量名。您需要将该值赋给一个变量,并将其传递到doub

result = add1(value)
doub(result)

还要注意,Python不是C;没有打字这回事int是对值调用的函数:

value = int(input('Enter a number '))

相关问题 更多 >

    热门问题