AdventL AdventL - 5 days ago 6
Python Question

Creating functions, name not defined and passed by reference

I've been self-learning python and have gone through the Intro to Python course on Udacity and am currently practicing python problems on this site Praticepython.org

I'm currently at Exercise 10 and have decided to start putting things into a function to make things neater and hopefully more understandable.

However, I've run into a problem.

def getlistlen():
list1len, list2len = raw_input("Please input the lengths of the 2 lists, seperated by a space: ").split()
list1len = int(list1len)
list2len = int(list2len)
print(list1len)
print(list2len)
generatelist()


def generatelist():
print(list1len)
print(list2len)
list1 = []
list2 = []
for i in range(1, list1len+1):
list1.append(random.randint(1,100))

for i in range(1, list2len+1):
list2.append(random.randint(1,100))
print(list1)
print(list2)


I have tried defining the variables


  • list1len

  • list2len

  • list1

  • list2



outside of everything, but if I do that, the values don't change after the functions execute.

I've also tried declaring list1len and list2len under getlistlen() but the function generatelist() cannot retrieve the values for list1len and list2len.

How do I fix this?

From what I understand, variables from outside the functions will only change if what happens inside the function changes them, however, they will not change if they are redeclared inside the function.

Using Python 2.7.12, IDLE IDE.

Thanks!

Answer

You need to pass the defined variables into function generatelist() in order to use them. Try this code :

def generatelist(list1len,list2len):
    print(list1len)
    print(list2len)
    list1 = []
    list2 = []
    for i in range(list1len):
        list1.append(random.randint(1,100))

    for i in range(list2len):
        list2.append(random.randint(1,100))
    print(list1)
    print(list2)


def getlistlen():
    list1len, list2len = raw_input("Please input the lengths of the 2 lists, seperated by a space: ").split()
    list1len = int(list1len)
    list2len = int(list2len)
    print(list1len)
    print(list2len)
    generatelist(list1len,list2len)

Firstly define generatelist() and then use it into another function in order to calculate list.

Comments