【问题标题】:What is causing the error in this program是什么导致了这个程序的错误
【发布时间】:2016-04-06 23:32:45
【问题描述】:

我制作的程序有点问题。我不太确定问题是什么。但是,我想不出要寻找什么来解决问题。既然是这种情况,如果这是一个重复的问题,我提前道歉。

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

在第一个循环的华氏赋值语句之前,该程序运行良好。我确信问题涉及变量以及我分配它们的最可能不正确的方式。因此,如果有人能指出我做错了什么以及为什么它不起作用,我将不胜感激。

【问题讨论】:

  • 100 次中有 99 次,如果您尝试动态访问变量,那么您做错了。将输入保留为元组 (temperatures = eval(input(...))) 并对其进行迭代 (for temperature in temperatues:)

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


【解决方案1】:

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

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' 等等。它们不同于您在input 行中指定的名称c1c2。将用户输入的所有值放入temp 会更容易。不管是一、二、十还是一百。 Python允许直接循环temps

for c in temps:

这里c依次成为每个存储在temps中的数字。

【讨论】:

  • 感谢您的帮助。我对编程还是很陌生,还不知道什么可以做,什么不能做。
  • 欢迎来到 SO。你的尝试已经很不错了。我们都在这里学习。 :)
猜你喜欢
  • 2011-08-13
  • 2012-10-06
  • 2012-09-21
  • 2010-10-12
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多