while True: celsius = float(raw_input('Temperature in degrees Celsius: ')) fahrenheit = celsius * 9 / 5 + 32 print celsius, 'degrees Celsius is', fahrenheit, 'degrees Fahrenheit'The above loop will keep asking the user for a temperature, and coverting it to Fahrenheit. That's very nice, but the loop will run
while True
, which means forever. How do we get
out?
The user could always stop the program by typing Control-C, but this is ugly. Here are a couple of solutions:
while True: celsius = float(raw_input('Temperature in degrees Celsius, or -999 to stop: ')) if celsius == -999: break fahrenheit = celsius * 9 / 5 + 32 print celsius, 'degrees Celsius is', fahrenheit, 'degrees Fahrenheit'
while True: reply = raw_input('Temperature in degrees Celsius, or <Enter> to stop: ') if reply == '': break celsius = float(reply) fahrenheit = celsius * 9 / 5 + 32 print celsius, 'degrees Celsius is', fahrenheit, 'degrees Fahrenheit'Notice that we need a temporary string
reply
to check
for an empty line. We only try to convert non-empty
strings into a float
. Consider the previous
program:
while True: celsius = float(raw_input('Temperature in degrees Celsius, or -999 to stop: ')) if celsius == -999: break fahrenheit = celsius * 9 / 5 + 32 print celsius, 'degrees Celsius is', fahrenheit, 'degrees Fahrenheit'If the user had just pressed the <Enter> key, and we had tried to convert that empty string into
celsius
, the
program would have crashed with a ValueError
.