我刚刚开始学习python。我建立了一个基本的重量转换器,可以将重量公斤转换为磅或将磅转换为公斤。我有两个输入字段。如果用户输入错误,我只希望在第一个输入中接受值“ L”或“ K”,那么它将显示错误消息,如“请在k或L之间选择”,我也希望用户在第二个输入中输入任何字符串值字段,然后将显示错误消息,例如“请输入数字。您输入了字符串”
这是我的代码:
unit = input("Select (K)kilograms or (L)pounds: ").upper()
if unit == "L":
weight = int(float(input("give your weight: ")))
converted_weight = weight * 0.45
print(f"your weight {converted_weight} converted to kilograms")
elif unit == "K":
weight = int(float(input("give your weight: ")))
converted_weight = weight / 0.45
print(f"your weight {converted_weight} converted to pounds")
您可以使用while循环,如果没有从用户那里得到正确的输入,则可以显示您想要的错误消息。
这是完整的代码:
while True:
try:
unit = input("Select (K)kilograms or (L)pounds: ").upper()
if unit == "L":
weight = int(float(input("give your weight: ")))
converted_weight = weight * 0.45
print(f"your weight {converted_weight} converted to kilograms")
break
elif unit == "K":
weight = int(float(input("give your weight: ")))
converted_weight = weight / 0.45
print(f"your weight {converted_weight} converted to pounds")
break
elif unit != "K" or "L": #it will show error massage if user give anything except k or l
print(""please choose between k or L")
continue
except ValueError:
print("please enter number. You given string")
continue
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句