我在学习python时一直在阅读while循环。以下内容可以正常工作,但是如果我将16作为值插入,则会得到

Insert numbers only
Your weight is 16 lbs


这不正确

while True:
    weight_input = raw_input ("Add your weight: ")+(" lbs")
    try:
       val = int(weight_input)
    except ValueError:
        print("Insert numbers only")

    print("Your weight is " + weight_input + "!")


我想念什么?我正在尝试打印重量,如果value =其他,则为整数,然后发送错误。

更新

决定使用上面的表格。添加"lbs"时出现错误,有任何帮助吗? print(tabulate([[weight_input]+"lbs"], tablefmt='pipe', headers=('Weight')))

最佳答案

您正在将" lbs"添加到输入中,从而使变量weight_input "16 lbs"。您可以将“ lbs”添加到循环末尾显示的消息中:

while True:
    weight_input = raw_input ("Add your weight: ")
    try:
       val = int(weight_input)
    except ValueError:
        print("Insert numbers only")

    print("Your weight is " + weight_input + " lbs!")

关于python - 带有错误处理的Python While循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48389486/

10-12 14:20