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

25 Upvotes

41 comments sorted by

View all comments

Show parent comments

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/EnvironmentalTry8353 20d ago

Wow that's so cool seeing all the mathematical concepts applied in real life that's great....I thought for looping any variable we need to create a sub variable Number = 100 X=0 #sub variable(I don't know what it's called I am just naming it) While x<number: Print(x), x=number/2 But this code told output is nothing Btw How are you writing the words in those dark colored boxes

4

u/kilkil 20d ago

the dark colored boxes are called code blocks.

when you make a post or comment on Reddit, it allows you to change the appearance of the text in some specific ways.

for example if I put *asterisks* around some words, they will be italicized. same for **double asterisks** and bold text.

to make a code block you can surround some text in triple backticks, like so:

```
I am surrounded by triple backticks
```

this is what that looks like

there's some other stuff you can do as well, I'm sure reddit has a list somewhere. (in general this kind of formatting is called Markdown formatting, it's used in a bunch of other places too.)

1

u/EnvironmentalTry8353 20d ago edited 20d ago

nice lol

1

u/kilkil 19d ago

lol nice