python - How to use user input to end a program? -


i'm new python , writing program converts millimeters inches. continuous loop allows keep putting in numbers , correct converted measurement. want put if statement allow user type "end" end program instead of converting more units of measurement. how go making work (what python code allows exit written program , can used in if statement.)?

convert=float(25.4) while true:     print("*******mm*******")     mm=float(input())     results=float(mm/convert)     print("*****inches*****")     print("%.3f" % results)     print("%.4f" % results)     print("%.5f" % results) 

to end loop, can use break statement. can used inside if statement, since break looks @ loops, not conditionals. so:

if user_input == "end":     break 

notice how used user_input, not mm? that's because code has minor problem right now: you're calling float() before ever check user typed. means if type "end", you'll call float("end") , exception. change code this:

user_input = input() if user_input == "end":     break mm = float(user_input) # calculations , print results 

one more improvement can make: if want user able type "end" or "end" or "end", can use lower() method convert input lowercase before comparing it:

user_input = input() if user_input.lower() == "end":     break mm = float(user_input) # calculations , print results 

make changes, , program work way want to.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -