[英]Python passing return values to functions
I'm trying to make a program that will generate a random list, length being determined by user input, that will be sorted. 我正在尝试制作一个程序,该程序将生成一个随机列表,其长度由用户输入确定,并将对其进行排序。 I'm having a problem accessing/passing my randomly generated list to other functions.
我在访问/将我随机生成的列表传递给其他函数时遇到问题。 For example, below, I can't print my list x .
例如,在下面,我无法打印列表x 。 I've also tried making a function specifically for printing the list, yet that won't work either.
我也尝试过制作一个专门用于打印列表的功能,但是那也不起作用。 How can I pass the list 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()
x = listgen(y)
def main():
y = int(input("How long would you like to make the list?: "))
x = listgen(y)
print(x)
x should be assigned based on return value of your function x应根据函数的返回值进行分配
l = listgen(y)
print(l)
The variable x
is local to listgen()
. 变量
x
是listgen()
局部变量。 To get the list inside of main()
, assign the return value to a variable. 要在
main()
获取列表,请将返回值分配给变量。
In your main, this: 在您的主体中,这是:
def main():
y = int(input("How long would you like to make the list?: "))
listgen(y)
print(x)
should be: 应该:
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)
Does that make sense? 那有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.