是什么导致此程序中的错误

时间:2016-01-03 02:34:11

标签: python variables python-3.x variable-assignment

我在制作一个程序时遇到了一些麻烦。我不太清楚问题是什么。但是,我想不出要搜索什么来解决问题。既然如此,如果这是一个重复的问题,我会提前道歉。

# 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()

这个程序可以正常工作,直到第一个循环上的华氏温度赋值语句。我确信问题涉及变量以及我分配它们的最可能的错误方式。如果有人能够指出我做错了什么以及为什么它不起作用,我将非常感激。

1 个答案:

答案 0 :(得分:2)

非常接近,但不要转换为字符串:

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()

不建议使用eval,因为用户可以执行任意Python代码。更好地明确转换数字:

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

此:

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

创建字符串'c1''c2'等等。它们与您在c1行中指定的名称c2input不同。将用户输入的所有值放在temp中更容易。如果它是一,二,十或一百并不重要。 Python允许直接循环temps

for c in temps:

此处c依次成为temps中存储的每个数字。