Skip to main content
 首页 » 编程设计

Python 2.7.5 正确的循环语法,正确使用 'while'

2025年05月04日15hnrainll

学习 python 中的循环,我正在使用的书刚刚介绍了“while”语句,为入门编程课做题,我需要获取用户输入的摄氏温度并将其转换为华氏温度并添加总和一起转换的温度,在我的伪代码中它是有道理的,但我在应用“while”语句时遇到了问题,到目前为止我有这段代码并且想知道是否有一种简单的方法来执行这种循环,但语法是'为申请工作。 这是到目前为止的代码。此外,该问题要求使用 -999 作为标记以退出程序并显示您的总计(温度的华氏转换总和以及转换后的温度总和)

sum = 0 #start counter at zero?  
 
temp = raw_input('enter temp in celsius, enter -999 to exit: ') #ask user for temp   
 
while temp != -999: #my while statement, sentinel is -999  
    faren = 9 * temp / 5 + 32 
    sum += temp #to accumulate the sum of temps?  
    total = sum + temp #for the total, does this go below?  
    print raw_input('enter temp in celcius, enter -999 to exit: ') #the loop for getting another user temp 
 
print faren #totals would be displayed here if user enters -999  
print total  
 
#need to use the "break" statment?  

请您参考如下方法:

raw_input()返回一个 str 对象。所以,当你传递-999时,它真的给了你"-999",它不等于-999。您应该使用 int() 函数将其转换为整数:

temp = int(raw_input('enter temp in celsius, enter -999 to exit: ')) 

此外,在 while 循环中,不要打印 raw_input 函数的结果,您应该将其重新赋值给 temp,否则你会陷入无限循环。