简体   繁体   中英

Python 2.7.5 correct loop syntax, proper use of 'while'

learning loops in python, book I'm using just introduced the "while" statement, doing problem for intro programming class, I need to get user input for a temperature in celsius and convert that to Fahrenheit and add the total of the converted temps together, In my psuedocode it makes sense but I'm having trouble with applying the 'while' statement, I have this code so far and am wondering if there is a simple way to do this kind of loop, but the syntax isn't working for application. Here is the code so far. Also, the problem asks to use -999 as the sentinel to exit the program and display your totals (the Fahrenheit conversion total of the temps and the total sum of the converted temps)

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() returns a str object. So, when you pass -999 , it really gives you "-999" , which is not equal to -999 . You should use the int() function to convert it to integer:

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

Also, inside the while loop, instead of printing the result of raw_input function, you should re-assign it back to temp , else you would fall into an infinite loop.

Other than the int/str issue mentioned by other answers, yyour problem is you never modify the temp variable. On the last line of your loop, you should do:

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

again!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM