Here I have some simple code that worries me, look at the second to last line of code, I have to return spam in order to change spam in the global space. Also is it bad to be writing code in this space and I should create a function or class to call from that space which contains most my code?
I found out very recently that I never even understood the differences between Python's identifiers compared to C or C++'s variables. This helps put into perspective why I always have so many errors in Python.
I do not want to continue writing code and get into a bad habit and this is why I want your opinion.
I also have a tendency to do things like spam = fun()
because I do not know how to correctly make Python call a function which changes a variable in the scope of where the function was called. Instead I simply return things from the functions never learning how to correctly write code, I want to change that as soon as possible.
import random
MAX = 20
def randomize_list(the_list, x=MAX):
for i in range(len(the_list)):
the_list[i] = random.randint(1, x)
def lengthen_list(the_list, desired_length, x=MAX):
if len(the_list) >= desired_length:
print "erroneous call to lengthen_list(), desired_length is too small"
return the_list
while(len(the_list) < desired_length):
the_list.append(random.randint(1, x))
# organize the_set
the_list = set(the_list)
the_list = list(the_list)
return the_list
spam = list(range(10))
randomize_list(spam, MAX)
print "the original list:"
print spam, '\n'
spam = set(spam)
spam = list(spam)
print "the set spam:"
print spam
print "the set spam with length 10"
spam = lengthen_list(spam, 10, MAX)
print spam
Please help me adopt a style which correctly fixes, in particular, the second to last line of code so that I do not need the function to do return things in order to work, if this is even possible.