简体   繁体   中英

non type error when trying to write a function that calls other functions and concatenates with string values and writes the results to a file python

I am trying to write a program which takes the data the from one file and creates another file and writes the data into the new file. The data from the first file is a string like this "Min: [1,2,3,5,6] on line one Max: [same list as the first line] and Avg: [same list as the first] My task to find the min, max, and average of this list and then write it to a new file in the format: "The min of [1,2,3,5,6] is 1" etc. The first line had random characters before it so I had to use strip method to get rid of those hence my first function looks the way it does. The program runs fine until it breaks at the last function which give me an error "cannot concatenate non-type with string and that error comes from the last function that was defined in the code. Please shed light on the error message.

def create_dictionary(file):
 with open("input.txt", "r", encoding = "utf-8") as file:
    for line in file:
        line_list = line.lstrip("\ufeff")
        line_list = line_list.rstrip("\n")
    return line_list.lstrip("avg :")
        
    
def integer_list(numbers):
      num_list = numbers.split(",")
      cast_int = [int(i) for i in num_list]
     return (cast_int)
  
def min_value(new_list):
    print(min(new_list))


def max_value(new_list):
     print(max(new_list))

def average(avg):
    avg = sum(new_list)/len(new_list)
    print(avg)

def write_to_file(minimum, maximum, mean):    
        with open("output.txt", "w") as file_output:
           output =  file_output.write("The min of" + string_list + "is" + minimum + "\n" + 
          "The max of" + string_list + "is" + maximum + "\n" + "The avg of" + string_list + "is" + mean)
    return output

 file = ''
 num_list = []
 cast_int = []
 avg = 0
 file_output = ''
 string_list = "[1,2,3,5,6]"


 numbers = create_dictionary(file)
 new_list = integer_list(numbers)
 minimum = min_value(new_list)
 maximum = max_value(new_list)
 mean  = average(avg)

 write_to_file(minimum, maximum, mean)

Your functions min_value/max_value only use the "print" function, which does not return anything. Therefore minimum/maximum are not defined and have no type. Try this:

def max_value(new_list):
 return max(new_list)) # this is the important line as it returns the value

Once you do that as well for the min_value function, you will obtain the correct values in maximum/minimum as numbers. To convert them to a string use the str() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM