Kordan9090
Kordan9090

Reputation: 55

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. 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?

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()

Upvotes: 1

Views: 70

Answers (3)

Aaron Hall
Aaron Hall

Reputation: 394795

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?

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361556

l = listgen(y)
print(l)

The variable x is local to listgen(). To get the list inside of main(), assign the return value to a variable.

Upvotes: 0

dm03514
dm03514

Reputation: 55932

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

Upvotes: 2

Related Questions