-1

I am new to python and trying to code an assignment but ran into some troubles.

What I was trying to do so far are import a file into the program, return it to the main().

I created another function call print_names() to print the names in list one per line and single-spaced and I tried to sort the contents from the file in alphabetical order (I was asked to do the sorting in main()).

Then now what I want to do is to pass that sorted list into another function so that I can put them in a new output file.

def main():
    names_in()                          # This function import the file and read all the content and put the content into a list.   
    print_names(names_in)               # Before the names are sorted.    
    names_sorted = sorted(names_in())   # Sort the list of names.   

    for item in names_sorted:           
        print(item)       

def names_in():
    infile = open('names.txt','r')
    names_list = []                     # empty list.
    names = infile.readline()           # read contents.

    # loop for continue to read.
    while names != '':
        names = infile.readline()       # continue to the next name.
        names = names.rstrip('\n')      # return a copy of the string which all \n has been stripped from the end of the string.
        names_list.append(names)        # write names in the file into a list.
    return names_list                   # return the list back to the function. 

    infile.close()                      # close the file.

def print_names(names_in):              # This function will print out the names in the list one per line, single-spaced.
    for item in names_in():
        print(item)


main()
Casimir Crystal
  • 18,651
  • 14
  • 55
  • 76
Minh Le
  • 29
  • 4

1 Answers1

-1

When you return a value from a function, you need to assign that to a variable, otherwise, you are ignoring it (something which is sometimes done). A completely untested rewrite:

def main():
    names = names_in()            # This function import the file and read all the content and put the content into a list.   
    print_names(names)            # Before the names are sorted.    
    names_sorted = sorted(names)  # Sort the list of names.   

    for item in names_sorted:           
        print(item)       
Hack Saw
  • 2,508
  • 1
  • 16
  • 30