2013-10-21 94 views
1

在Python學習循環,本書我剛剛介紹了「while」語句,爲介紹編程類做問題,我需要獲取用戶輸入溫度以攝氏度爲單位,並將其轉換爲華氏度,並將轉換後的臨時溫度總和加在一起,在我的psuedocode中它是有意義的,但我在應用'while'語句時遇到了麻煩,至今我有這個代碼,想知道是否存在一種簡單的方法來做這種循環,但是語法不適用於應用程序。 這是迄今爲止的代碼。此外,該問題要求使用-999作爲定點退出該程序並顯示您的總數(在華氏轉換總的臨時工和轉換臨時工的總和)Python 2.7.5正確的循環語法,正確使用'while'

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? 
+0

此外,我會使用9.0和5.0和32.0來避免舍入錯誤。 –

回答

6

raw_input()返回str對象。所以,當你通過-999,它真的給你"-999",這不等於-999。您應該使用int()功能,將其轉換爲整數

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

此外,while循環中,而不是打印raw_input函數的結果,你應該重新分配回temp,否則你會陷入一個無限循環。

+0

另外,確保可以在循環中更改'temp'。現在你正在打印字符串,但不會將其重新分配給'temp',因此這將永遠循環。 –

2

除了其他答案提到的int/str問題之外,你的問題是你永遠不會修改temp變量。在你的循環的最後一行,你應該這樣做:

temp = raw_input('enter temp in celsius, enter -999 to exit: ') #ask user for temp 

再次!