0

I have ran into some problems while trying to combine while loop and ValueError. Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.

number = 1

while number < 10:
    add = int(raw_input("Enter a number to add: "))
    number += add
    print number
else:
    print "Number is greater than 10"

I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?

number = 1

while number < 10:
    while True:
        try:
            add = int(raw_input("Enter a number: "))
            number += add
            print number
        except ValueError:
            print "Please enter a number"
else:
    print "Number is greater than 10"

Thank You.

1 Answer 1

1

there's an extra while True: loop resulting in an infinte loop.

Remove it and your code will work fine.

Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead

    number = 1

    while True:
        try:
            add = int(raw_input("Enter a number: "))
            number += add
            print number
            if number>10:
               break
        except ValueError:
            print "Please enter a number"

    print "Number is greater than 10"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.