I'm new to python and I am writing a program that converts Millimeters to Inches. Basically its a continuous loop that allows you to keep putting in numbers and get the correct converted measurement. I want to put an IF statement that will allow the user to type "end" to end the program instead of converting more units of measurement. How would I go about making this work (what python code allows you to exit a written program and can be used in an 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)
stop program python stop = input("Would you like to stop the program? ")
end = '\n' within input() functions Or just incorporating \n in any way within strings inside the function. If you want to create a new line in the text prompting for the input, you can't use 'end = ' as input has no parameter of that sort. Or if you want to take multiline input: import sys text = sys. stdin.
The exit() function is a cross-platforms function that is used to terminate program execution in Python. We can also use the exit() function in the Python interactive shell to end program execution and opt out of the Python interactive shell as shown below.
To end the loop, you can use a break
statement. This can be used inside an if
statement, since break
only looks at loops, not conditionals. So:
if user_input == "end":
break
Notice how I used user_input
, not MM
? That's because your code has a minor problem right now: you're calling float() before you ever check what the user typed. Which means if they type "end", you'll call float("end") and get an exception. Change your code to something like this:
user_input = input()
if user_input == "end":
break
MM = float(user_input)
# Do your calculations and print your results
One more improvement you can make: if you want the user to be able to type "END" or "End" or "end", you can use the lower() method to convert the input to lowercase before comparing it:
user_input = input()
if user_input.lower() == "end":
break
MM = float(user_input)
# Do your calculations and print your results
Make all those changes, and your program will work the way you want it to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With