Benjamin Jones
Benjamin Jones

Reputation: 997

Python- While Loop with error handling

Ive been reading up on while Loops while learning python. The following works without error, however if I insert 16 as value, I get

Insert numbers only
Your weight is 16 lbs

This is not correct

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 + "!")

What am I missing ? I am trying to print out weight and if value = anything other then a integer then send error.

UPDATE

Decided on using tables with above . I get a error adding "lbs" Any help? print(tabulate([[weight_input]+"lbs"], tablefmt='pipe', headers=('Weight')))

Upvotes: 1

Views: 9379

Answers (3)

Sphinx
Sphinx

Reputation: 10729

You have to remove the trailer=(" lbs") of raw_input first, then check if the input is one number by .isdigit().

while True:
  weight_input = raw_input ("Add your weight (type 'end' to exit'): ")
  if weight_input === 'end':
    break #use 'break' to quit the loop
  if not weight_input.isdigit():
    print("Insert numbers only")
  else:
    print("Your weight is " + weight_input + " lb!")

Upvotes: 1

Alex
Alex

Reputation: 19104

You are adding " lbs" to the input which makes the variable weight_input "16 lbs". You can add the "lbs" to the message that you display at the end of the loop:

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!")

Upvotes: 5

When you do

weight_input = raw_input ("Add your weight: ")+(" lbs")

You're adding the +(" lbs") to your input string. Try removing that.

Upvotes: 3

Related Questions