赋值语句不继承函数 python 3.1



我在Windows 3.1设备上使用python 10,遇到了问题。

当我使用在我所做的另一个函数中定义的赋值时,该赋值不起作用。我的问题在一长行代码中,但我制作了一个较小的版本来帮助解释正在发生的事情。

def test():
    """ takes input """
    f = input("1 or 2? ")
    if f == 1:
        t = "wow"
    if f == 2:
        t = "woah"
def test2(t):
    """ Uses input """
    print(t)
def main():
    test()
    test2(t)
main()
input("nnPress enter to exit" )

我不确定为什么程序在选择输入后不使用赋值"t"。

我的目标是使用第一个函数的输入来更改第二个函数的结果。 当然,我的原始程序比简单的打印功能更复杂,但我知道这个演示会搞砸我的程序。我的原始程序处理打开.txt文件,输入是选择要打开的文件。

任何帮助将不胜感激。

您必须返回"t"才能在test2中使用它:

def test():
    """ takes input """
    f = input("1 or 2? ")
    if f == '1':
        t = "wow"
    if f == '2':
        t = "woah"
    return t  # This returns the value of t to main()
def test2(t):
    """ Uses input """
    print(t)
def main():
    t = test()  # This is where the returned value of t is stored
    test2(t)    # This is where the returned value of t is passed into test2()
main()
input("nnPress enter to exit" )

最新更新