Home > Back-end >  TypeError: can only concatenate list (not "str") to list : Python
TypeError: can only concatenate list (not "str") to list : Python

Time:05-27

I was trying to bubble sort the temperature array but i am getting this kind of error.. Someone please help me fix this :)

Here's the code :

print("")
print("")

days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"]
temperature = []
highest = float(0.0)
lowest = float(100.0)
total = float(0.0)  

for i in range(7):
    inp = round(float(input("Please enter the temperature for "   days[i]   " in Celcus: ")),1)
    temperature.append(inp)
    


print("")
print("")
    
print("You entered these Temperatures in Celsius and Fahrenheit.")

print("")
print("")


for j in range(len(temperature)):
    
    def bubble_sort(tem):
        for a in range(len(tem)):
            for b in range(len(tem)-1):
                if(tem[b]>tem[b 1]):
                    temp=tem[b]
                    tem[b]=tem[b 1]
                    tem[b 1]=temp
        return tem
    arr = []
    arr.append(temperature[j])
    Fahrenheit = round(((temperature[j] * 1.8)   32),1)
    total = total   temperature[j]
    print(bubble_sort(arr)   " C° is "   str(Fahrenheit)   " F°" )
    
print("--------------------")
avg = round(total / len(temperature),1)
print("High Temp: "   str(max(temperature))   "C°, Low Temp: "   str(min(temperature))   " C° Average Temp: "   str(avg)   " C°")

I am not getting what wrong is with this code ..

CodePudding user response:

The error is pretty explicit: the list is bubble_sort(arr) and the str is " C° is "

You can't concatenate them at bubble_sort(arr) " C° is ", you'd need to wrap the list into str


The nicest is just to use the fact that print allows multiple values to be given

print(bubble_sort(arr), "C° is", Fahrenheit, "F°")

print("High Temp:", max(temperature), "C°, Low Temp:",
      min(temperature), "C° Average Temp:", avg, "C°")

Now, you're not sorting anything as there is only ONE value in arr, just sort once before the loop, then show the Fahrenheit value

arr = bubble_sort(temperature)
for value in arr:
    fahrenheit = round(((value * 1.8)   32), 1)
    print(value, "C° is", fahrenheit, "F°")

avg = round(sum(temperature) / len(temperature), 1)
print("High Temp:", max(temperature), "C°, Low Temp:",
      min(temperature), "C° Average Temp:", avg, "C°")

CodePudding user response:

the defectiv line is

print(bubble_sort(arr)   " C° is "   str(Fahrenheit)   " F°" )

since you are using the " " operator on a list and a string in order to fix it try converting the list (that you get from calling "bubble_sort(arr)" to a string )

like this

print(''.join(str(e) for e in bubble_sort(arr))   " C° is "   str(Fahrenheit)   " F°")
  • Related