1

No matter what I do, I can't get this while loop to work; unless i hardcode the value in.

count = 0
value = raw_input('How many?')
print value
while (count <= value):
        print "a"
        count= count + 1

At first I tried using a command line argument, using sys.argv[1] for value but I got the same problem. This seems so simple, yet I cannot for the life of me figure out what I'm doing wrong.

2
  • Try to check - what type is your value? And what type is your count variable? Commented Sep 4, 2012 at 10:20
  • After fixing the datatype issues mentioned by others, there's a slightly more concise and pythonic way to write the loop: for i in xrange(value): print "a". Commented Sep 5, 2012 at 3:33

3 Answers 3

9

Ensure that value is an integer,

while (count <= int(value)):
    count= count + 1

By default raw_input is a string, and for every integer n and every string s we have n<s is True (!), hence your loop (without the int) never breaks.

Note: In Python 3 comparing string and integers will give a TypeError: unorderable types: str() < int(), which is probably more "expected" behaviour.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I didn't even think about that.
Also note that this now behaves a bit better in Python 3 - '5' < 4 gives an error that tells you exactly what's going on, rather than a meaningless result.
1

Convert your input to an integer first

value = int(raw_input('How many?'))
print value

1 Comment

... but dont' forget to try->catch the possible ValueErrorException, which can be raised if the input is not a number representation!
1

By the way, if you really want to get your statement to be value times printed change condition from

count <= int(value)

to

count < int(value)

or start count from 1

Comments

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.