Question
While You’re Here: link to exercise
Answer
We include count += 1
inside the while
loop so that eventually count
becomes 10
and our loop condition becomes False
. Otherwise, count
will never be 10
or greater and our loop will continue on forever!
Take care when writing while
loops in the future and make sure you indent within the loop some change to your condition to avoid infinite loops!
2 Likes
Can I use range(10) in the while loop?
I tried but it gives me error
2 Likes
while count in range(10):
print “Hello, I am a while and count is”, count
count += 1
it seems to be working
3 Likes
I used for loop instead of while
Irrespective of count+=1, output remains same.
How ?
while simply asks “is the condition true?” In the case of count in range(10)
it will be true for ever and ever if you have already set count to an int between 0 and 9, inclusive, and have done nothing to change it.
for-in, on the other hand, does so much more
-
It looks at the sequence on the right of in,
-
and turns it into an iterator - something that will tick on down the line every time you look at it with the keyword next, that is, if it isnt an iterator already, as range() actually is,
-
and then, “under the hood,” provides that next each time around,
-
and then assigns that next value to the iteration variable (count, in this case) you have put before in,
-
and knows when to stop when the iterator is empty .
-
All the while, it ignores any tampering you might be trying to do with your iteration variable, such as count += 1
, or count += 100
.
1 Like
Thanks a lot for mentioning last point. (All the while, it ignores any tampering you might be trying to do with your iteration variable, such as count += 1
, or count += 100
). Got clear now.
Yes, you can use it, but with for: for x in range(11):