无法打印python中上一个函数中的变量

2024-09-29 19:02:52 发布

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

我有一个数据库程序来保存数据,但我无法解决这个问题:

我有两个函数。当您在程序中输入 名为addy()的函数启动 并要求对变量进行更多输入 然后返回主屏幕, 然后用户可以输入S 哪个节目开始 然后,它应该显示您添加到变量中的内容

问题: 它没有从前面的定义中获取值

代码:

def addy():
    os.system('cls')
    addel = input('what is the name of the operating system?: \n')
    os.system('cls')
    time.sleep(1)
    print(addel + ' Has been added to the database!')
    time.sleep(2)

    program()


def show():
    
    print('Heres a list of the operating systems you have added:')
    time.sleep(5)
    program()
    addel = addy()
    print(addel)  # this should print the value from the previous function

Tags: ofthe函数程序addedtimeosdef
1条回答
网友
1楼 · 发布于 2024-09-29 19:02:52

原因有两个

  1. Addel是局部变量而不是全局变量。因此,您只能在addy函数中使用它
  2. 说你的意图是不使用它,这就是它看起来的样子,你写道
addel = addy()

函数addy没有返回值,因此代码无法工作。 要解决此问题,请编写

return addel

作为addy函数中的最后一行,它将工作,因为现在函数有一个返回值

相关问题 更多 >

    热门问题