我在学习 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 + "!")
我错过了什么?我正在尝试打印出重量,如果值 = 任何其他值则为整数,然后发送错误。
更新
决定使用上面的表格。我在添加 "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!")
