Please help me improve this code

My code works. It reads in a textfile of letters (eg alphabet) and creates a new textfile of the same letters in random order.
I have used functions and global variables.
Please help me by teaching me how to pass the correct parameters into my functions so the code still works but without using global variables.

def readfile():
    print('Reading File')
    global listlines
    f = open('alphabetSorted.txt')
    for line in f:
        #print(line.strip())
        listlines.append(line)
    #print(listlines)
    f.close()


def makerandom():
    print('Randomising Data')
    global newlist
    newlist = listlines.copy()
    random.shuffle(newlist)
    #print('NEWLIST',newlist)
     

def writefile():
    print('Writing File')
    global newlist
    f = open("alphabetRandom.txt", "w")
    #print(newlist)
    f.writelines(newlist)
    f.close()


def main():
    readfile()
    makerandom()
    writefile()


#########################
import random
listlines=[]
newlist =[]
main()

If you don’t want to use global variables, then use parameters and return statements.
Here’s my solution:

def readfile():
    print('Reading File')
    listlines = []
    f = open('alphabetSorted.txt')
    for line in f:
        listlines.append(line)
    f.close()
    return listlines


def makerandom(listlines):
    print('Randomising Data')
    
    # since you're not using this "newlist" elsewhere in the code, you can actually shuffle listlines directly
    newlist = []
    newlist = listlines.copy()
    random.shuffle(newlist)
    return newlist
     

def writefile(newlist):
    print('Writing File')
    f = open("alphabetRandom.txt", "w")
    f.writelines(newlist)
    f.close()


def main():
    listlines = readfile()
    listlines = makerandom(listlines)
    writefile(listlines)


#########################
import random
main()

I hope this helps, if you have any problem in understanding parameters or return statements, do not hesitate to tell me and I will explain further.

1 Like

Thank you so much for your help. Forums are great. I always get help from forums.

You just taught me that it is possible to write a function that does not have arguments but returns a value. That confused me for a bit.

After watching a YouTube https://www.youtube.com/watch?v=tUiE3KrvqU0&t=917s
I understood better. The video’s example is getting the time.

Happy to help! Keep up the good work and happy coding :slight_smile:

1 Like