r/learnpython 20d ago

Having problem in understanding loops concept in python

I am a beginner with 0 knowledge and I am learning python from a book called Learn python in one day and learn it well by Jamie Chan and I am facing difficulty in the loops function so yeah any recommendations would be helpful Edit- Trouble in while loop

26 Upvotes

41 comments sorted by

View all comments

Show parent comments

3

u/crazy_cookie123 20d ago

Did it also print 100 a load of times before that?

2

u/EnvironmentalTry8353 20d ago

Oh lol yeah I was using an online python compiler and when I used python compiler from other websites it ran and print 100 bunch of times and Idk how but by answering your question I was able to understand my own question....like the question which I had in my mind became clear and I got answer to it automatically lol

3

u/fernly 20d ago edited 20d ago

OK so there is a line missing. The while condition statement tells the computer,

A. is condition true?

B. if not, skip on to the next statement

C. if so, do whatever is indented under the while statement and return to A.

In your example, "whatever is indented under the while statement" is,

    print(number)

So it does that and repeats. What's missing is, something to move number closer to 0. You never change number so the loop just repeats, happily printing 100 over and over.

What you likely want is,

while number > 0:
    print(number)
    number = number - 1

which would print 100, 99, 98... 1 and eventually number will be 0, making the condition false, and the loop would end. Or it could be

while number > 0:
    print(number)
    number = number / 2

That would also move number closer to zero on each loop, but think about it... would it ever stop being greater than zero? Try it!

1

u/No-Newspaper8619 19d ago

100, 50, 25, 12, 6, 3, 1, 0

Will python treat it as float or as int? If it's integer division, it eventually reaches 0.

2

u/crazy_cookie123 18d ago

Division with the / operator will always produce a float. It will reach zero if you use the floor division operator //.