1

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')))

1
  • 1
    The value of weight_input is "16 lbs". That's not a valid integer Commented Jan 22, 2018 at 20:13

3 Answers 3

5

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!")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that worked! Sorry for dumb question. How do I end the loop?
You can use the keyword break. See the docs on control flow.
I did the following above. Decided on using tables . I get a error adding "lbs" Any help? print(tabulate([[weight_input]+"lbs"], tablefmt='pipe', headers=('Weight')))
3

When you do

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

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

1 Comment

Try removing that - Is this an answer that you know works or are you guessing? Maybe you should format this as an answer instead of a suggestion.
1

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

1 Comment

While this is valid, Pythonistas tend to prefer the EAFP approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.