somethingsomewhere
somethingsomewhere

Reputation: 60

How do I add a conversion factor to each element in a list?

I am trying to add a conversion factor (F to C) to a list generated from user input to output as a separate list. How do I do this?

I'll put some code down for what I currently have

userEntry = int(input("Please enter a fahrenheit:"))

listofFahrs =[userEntry]

for i in range(4):
    i +=1
    listofFahrs.append(int(input("Please enter another fahrenheit:")))
    # convert to string if need be for output
    userList = str(listofFahrs[0:6])


fahrToCels =(userEntry - 32) * 5 / 9
celsConversion = [x + fahrToCels for x in listofFahrs]

When I tried print(celsConversion) I got some weird behavior... For instance, entering just 1 for all 5 integers produced -16.2 , which is 1 degree HIGHER than what the conversion is supposed to be (i.e. it was supposed to output -17.2

And when I try to enter a list such as 1,2,3,4,5...it seems to add one and give me the list back..

At this point I've compensated by adding -1 to fahrtoCels but I'm wondering if there's any cleaner way to do this.

Thanks in advance if you can help!

Upvotes: 0

Views: 56

Answers (1)

Shijith
Shijith

Reputation: 4872

Create a function which takes in Fahrenheit values and return Celsius values, pass every element in your listofFahrs to that function using list comprehension.

def fahrToCels(fahr):
    return round((fahr - 32) * 5 / 9,2)

listofFahrs =[]
for i in range(5):
    listofFahrs.append(int(input("Please enter a fahrenheit value:")))

celsConversion = [fahrToCels(x)  for x in listofFahrs]

Upvotes: 1

Related Questions