Python输出的值不正确

0 投票
2 回答
963 浏览
提问于 2025-04-18 02:54

我遇到的问题是这样的:

供电公司会通过“加热度”和“冷却度”来估算能耗。简单来说,如果一天的平均温度低于60华氏度,那么低于60的温度差就会被加到加热度里;如果温度高于80华氏度,那么超过80的部分就会加到冷却度里。现在我需要写一个程序,输入一系列的每日平均温度,然后计算出加热度和冷却度的总和。最后,程序应该在处理完所有数据后打印出这两个总和。

但是,当我运行程序时,可以输入温度,但当我按下回车键表示输入结束时,程序却返回“未知错误”。谢谢大家的帮助。

def main():
print("Please enter daily average temperature below. Leave empty when finish.")

hdd,cdd,hot,cool = 0,0,0,0
date = 1
try:
    temp = input("Day #{} :".format(date))

    while temp != "":
        temp = int(temp)

        if temp > 80:
            cdd = (temp-80)+cdd
        if temp < 60:
            hdd = (60-temp)+hdd

        date = date+1
        temp = input("Day #{} :".format(date))

    print("In {} days, there\'r total of {} HDD and {} CDD.".format(date-1,hdd,cdd))

except ValueError:
    print('Please correct your data.')
except:
    print('Unknown error.')

main()

2 个回答

0

这个错误是因为你在使用 Python 2.7 的 input() 函数。它出现了这个错误:

SyntaxError: unexpected EOF while parsing

不过你的程序不会显示这个错误,因为你最后的 except 语句把它给隐藏了。

错误的原因是,Python 2.7 中的 input() 函数实际上是获取输入并执行它。在你的情况下,它试图执行一个空输入。

你可以使用 raw_input(),这样你的代码就能正常运行了。

关于 Python 2.7 中 input() 函数的更多错误细节,可以查看这里 - 为什么按回车时 input() 会出错?

0

raw_input() 替代 input()。你的 temp 变量在为空的时候(因为它是"")试图变成一个整数,这样会出问题。

出现语法错误是因为 input() 会尝试计算你输入的内容。而你应该使用 raw_input(),然后把得到的值转换成你需要的类型,直到你确定真的需要用 input() 来做某些特定的事情。

把所有的 input() 改成 raw_input() 后:

Day #1 :1
Day #2 :2
Day #3 :3
Day #4 :90
Day #5 :90
Day #6 :
6 174 20
In 5 days, there'r total of 174 HDD and 20 CDD.

撰写回答