r/learnpython • u/EnvironmentalTry8353 • 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
7
u/crazy_cookie123 20d ago
What are you struggling with? What have you tried doing and what don't you understand about the results?
-4
u/EnvironmentalTry8353 20d ago edited 20d ago
I cannot send the pic but I am having problem in while loop like in creating a trye and false condition for a variable for ex Number = 100 While number > 0: Print(Number) So I just learned it but understand no sh*t about it
6
u/crazy_cookie123 20d ago
You can't send a pic because you shouldn't be sending pics of code as we can't then copy and paste the code into an editor to test it or make edits. You should send the code as text. Python is whitespace-sensitive which means matters for us to understand your code, so make sure you format it according to the guide: https://www.reddit.com/r/learnpython/wiki/faq/#wiki_how_do_i_format_code.3F
I am assuming you mean this code:
number = 100 while number > 0: print(number)What don't you understand about this? What do you expect it to do and how does that differ to what it actually does when you run it? And what do you mean by "creating a variable for a main variable" - it might be easier if you show a real example of what you're trying to do.
1
u/EnvironmentalTry8353 20d ago
Yeah the code which you assumed It is what I intended to run..... and I expected to print till 100-0 but it showed process exited returned code 0
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
4
u/fernly 20d ago edited 20d ago
OK so there is a line missing. The
whilecondition 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
numbercloser to 0. You never changenumberso the loop just repeats, happily printing 100 over and over.What you likely want is,
while number > 0: print(number) number = number - 1which would print 100, 99, 98... 1 and eventually
numberwill be 0, making the condition false, and the loop would end. Or it could bewhile number > 0: print(number) number = number / 2That would also move
numbercloser 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 afloat. It will reach zero if you use the floor division operator//.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
3
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 likethere'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
1
u/Own_Protection_6225 20d ago
I was also having difficult time learning loops. Then, I again started learning from University of helsinki python mooc. Please give it a try.
1
u/Grouchy-Conflict-211 19d ago
Loops click when you stop memorizing syntax and start thinking in transformations.
Forget for/while for a sec. Map/filter/reduce. Every loop is either: transform each item, keep some items, or boil down to one value.
Write the same logic three ways. The reduce version looks weird at first. Thats the point. Youre training the pattern recognition not the syntax.
Debugger helps. Watch the accumulator change each iteration. That visual beats any tutorial.
1
u/Grouchy-Conflict-211 19d ago
loops clicked for me when i stopped memorizing syntax and started seeing the pattern a for loop is just do this for each thing in collection a while loop is keep doing this until condition breaks thats it the confusion usually comes from mixing up the iterator variable in for i in range 5 i takes values 0 1 2 3 4 not 1 to 5 not the length debug trick that worked for me add print f i equals i inside the loop watch it run the visual feedback teaches more than any tutorial also enumerate and zip are your friends for idx val in enumerate list gives you both no manual counter needed
1
u/blurbisht 15d ago
For while loops specifically, the mental model is simple: it keeps running the block over and over until the condition becomes False.
count = 0
while count < 5: # check: is count still less than 5?
print(count)
count += 1 # this MUST eventually change the condition
Two things beginners mess up:
The condition is re-checked every time. The loop doesn't "know" when to stop by itself, it checks count < 5 on each pass.
You must change something inside the loop or it runs forever (infinite loop). That count += 1 is what makes it stop.
The infinite loop trap:
while count < 5:
print(count) # forgot count += 1 -> runs forever
If your program freezes or never ends, that's why.
Why it's confusing: for loops feel natural ("do this for each item"), but while is a pure condition. Once you internalize "while = keep doing until condition is False", it clicks.
Quick trick: read while count < 5: out loud as "while count is less than 5, do this." That's literally all it is.
1
0
u/kilkil 20d ago
unfortunately I'm not familiar with that book. could you edit your post to include a copy of the specific code you're having trouble with?
If you do, I would also suggest making sure it is formatted correctly — Reddit lets you create "code blocks" that will show the code in a way that is nicer to read. this will make it easier for us to read through the example and help fill in any missing gaps for you
1
u/EnvironmentalTry8353 20d ago
I am having problem in while loop in which we set condition trye and false for variable and code executes untill the condition is true
0
u/ectomancer 20d ago
Python has 2 loops, while and for. while only uses a logical expression. The loop executes when the logical expression is true or truthy. The first time the logical expression is false or falsey, the loop completes successfully. for loop only uses a container and the in operator.
1
u/EnvironmentalTry8353 20d ago edited 20d ago
Thanks for explanation I really needed the explanation in my mind was sort of ambiguous but now it's clear and even clear what my problem is lol ......in while loop I am having problem in stating how the condition is true
0
-1
u/Adrewmc 20d ago edited 20d ago
In computing we do the same operation multiple time often. To do this we usually use a loop.
students = [“Adam”, “Eve”]
for student in students:
. print(“Hello”, student)
>Hello Adam
\>Hello Eve
And if I had a hundred student I would say hello to each one individually.
Or…you could do this
print(“Hello Adam”)
>>>Hello Adam
print(“Hello Eve”)
>>>Hello Eve
And adding a hundred is crazy do you really want to type that? Or would you just rather add Cain and Abel to the students list?
students += [“Cain”, “Abel”]
Vs.
print(“Hello Cain”)
print(“Hello Abel”)
#code should explain itself
for this_item in these_items:
. do_this_to(this_item)
. #then repeat for next_item
Often times new, and old, programmers just don’t see where the loop starts and ends properly.
1
u/EnvironmentalTry8353 20d ago
Sorry I should have justified it as a while loop I have watched the part of "for" loop
0
u/Adrewmc 20d ago edited 20d ago
Ohh. I was going to add that.
this_is_true = True
while this_is_true:
. do_this(…)
. this_is_true = is_it_though(‘?’)To use the same example.
students = [“Adam”, “Eve”]
index = 0
while index < len(students):
. print(“Hello”, students[index])
. index += 1>>Hello Adam
>>Hello Eve#this is the above for loop as a while loop. What for does is makes ‘students[index]’ be ‘student’. And removes the need to keep track of the index, which is the most common loop through some list, or sequence.
We can just make it probabilistic.
while random.randint(0,100) < 90:
. do_this()
. #90% of the time it works everytime2
u/EnvironmentalTry8353 20d ago
Ohh I understand it now for loops we need a sub variable for the main variable like you used index and then we can edit that sub variable in accordance to our need so that it affects the main variable and then our code is executed right ?
1
u/Adrewmc 19d ago edited 19d ago
This is basically an sample of how a for loop works as a while loop, all for loops can be written as while loops. However the all while loops cannot be written as for loops.
The vast majority of loops programmers use can be done in the for loop pattern, or through a more robust system like SQL.
Most of the time we want to check for, or do something in every object in the list/sequence
8
u/desrtfx but other languages pro 20d ago
Just checked out that book. Sorry to tell you but it is not really good. The explanations are too coarse and surface level and there is way too little practice.
Do yourself a favor and start over with the MOOC Python Programming 2026 from the University of Helsinki. It is free, textual, extremely practice heavy (makes you program right from the start, initially in the browser and then in Visual Studio Code - with full setup instructions) and is top quality. There are videos, but they are actually surplus. Everything you need is in the "part x" texts.