Python将返回值传递给函数

时间:2014-03-20 17:37:04

标签: python

我试图创建一个程序来生成一个随机列表,长度由用户输入决定,将被排序。我在访问/将随机生成的列表传递给其他函数时遇到问题。例如,下面,我无法打印我的列表 x 。我也尝试过专门用于打印列表的功能,但这也不会起作用。如何通过列表 x

unsorted_list = []
sorted_list = []

# Random list generator
def listgen(y):
    """Makes a random list"""
    import random
    x = []
    for i in range(y):
        x.append(random.randrange(100))
        i += 1
    return x

def main():
    y = int(input("How long would you like to make the list?: "))
    listgen(y)
    print(x)


main()

3 个答案:

答案 0 :(得分:2)

x = listgen(y)

def main():
    y = int(input("How long would you like to make the list?: "))
    x = listgen(y)
    print(x)

应根据函数的返回值分配x

答案 1 :(得分:0)

l = listgen(y)
print(l)

变量xlistgen()的本地变量。要获取main()内的列表,请将返回值分配给变量。

答案 2 :(得分:0)

在你的主要内容中:

def main():
    y = int(input("How long would you like to make the list?: "))
    listgen(y)
    print(x)

应该是:

def main():
    y = int(input("How long would you like to make the list?: "))
    x = listgen(y) # Must assign the value returned to a variable to use it
    print(x)

这有意义吗?

相关问题