Inh*_*.Py 5 python if-statement python-3.x
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)
Run Code Online (Sandbox Code Playgroud)
要结束循环,可以使用break
语句。这可以在语句内使用if
,因为break
只查看循环,而不查看条件。所以:
if user_input == "end":
break
Run Code Online (Sandbox Code Playgroud)
注意到我是如何使用的user_input
,不是吗MM
?那是因为您的代码现在有一个小问题:您float()
在检查用户输入的内容之前调用。这意味着如果他们输入“end”,您将调用float("end")
并得到异常。将您的代码更改为如下所示:
user_input = input()
if user_input == "end":
break
MM = float(user_input)
# Do your calculations and print your results
Run Code Online (Sandbox Code Playgroud)
您还可以进行一项改进:如果您希望用户能够键入“END”或“End”或“end”,您可以使用该lower()
方法在比较之前将输入转换为小写:
user_input = input()
if user_input.lower() == "end":
break
MM = float(user_input)
# Do your calculations and print your results
Run Code Online (Sandbox Code Playgroud)
进行所有这些更改,您的程序将按照您希望的方式运行。