user4821942
user4821942

Reputation:

What is causing the error in this program

I am having a bit of trouble with a program that I made. I am not quite sure what the problem is. However, I cannot think of what to search for to solve the problem. Since this is the case, I apologize in advance if this is a duplicate question.

# convert.py
# A program to convert Celsius temps to Fahrenheit

def main():
    print("Hello", end=" ")
    print("this program will convert any 5 different celsius temperatures to fahrenheit.")
    c1, c2, c3, c4, c5 = eval(input("Please enter 5 different celsius temperatures seperated by commas: "))
    print(c1, c2, c3, c4, c5)
    for i in range(5):
        c = ("c" + str(i + 1))
        print(c)
        fahrenheit = 9/5 * c + 32
        print("The temperature is", fahrenheit, "degrees Fahrenheit.")
    input("The program has now finished press enter when done: ")

main()

This program works fine up until the Fahrenheit assignment statement on the first loop. I am sure that the problem involves the variables and the most likely incorrect way that I have assigned them. So I would greatly appreciate it if someone could point out what I am doing wrong and why it will not work.

Upvotes: 1

Views: 62

Answers (1)

Mike Müller
Mike Müller

Reputation: 85582

Pretty close, but don't convert to strings:

def main():
    print("Hello", end=" ")
    print("this program will convert any 5 different celsius temperatures to fahrenheit.")
    temps = eval(input("Please enter 5 different celsius temperatures seperated by commas: "))
    print(*temps)
    for c in temps:
        print(c)
        fahrenheit = 9/5 * c + 32
        print("The temperature is", fahrenheit, "degrees Fahrenheit.")
    input("The program has now finished press enter when done: ")

main()

It is not recommend to use eval as the user can execute arbitrary Python code. Better convert the numbers explicitly:

prompt = "Please enter 5 different celsius temperatures seperated by commas: "
temps = [int(x) for x in input(prompt).split(',')]

This:

c = ("c" + str(i + 1))

creates the strings 'c1', 'c2' and so on. They are different than the names c1and c2 you assign in the line with input. It is easier to put all values the user enters in temp. It does not matter if it is one, two, ten or one hundred. Python allows to loop of temps directly with:

for c in temps:

Here c become each number in turn that is store in temps.

Upvotes: 2

Related Questions