DEV Community

sridhar n
sridhar n

Posted on

Python Day 10 – Looping Is a Choice (and the while Loop)

Day 10 started with a mindset talk before any code, and I actually liked that.

The mindset part

Looping is just "doing the same thing again and again". If you need print(1) 300 times, you don't type it 300 times.

Our trainer also said:

  • Don't compare yourself with others
  • Ask questions. Repeat things until they make sense.
  • Use pen and paper

Ground rules for solving any problem

  1. Never say "I don't know". Say "Let me try".
  2. Don't think about the whole output. Think about the very next step.
  3. Introduce a variable when you need one.
  4. Micro to macro: start small.
  5. Dry run on paper before running.
  6. Every program has 3 parts: Input → Process → Output
  7. Logic first, syntax next.

Python has while and for. There is no do...while.

And one important line: only use a loop when it actually reduces your effort. If you just need 1 1 1 1 1, then print("1 1 1 1 1") is perfectly fine.

The while loop

count = 0
while count < 5:
    print(1, end=' ')
    count = count + 1
Enter fullscreen mode Exit fullscreen mode

Output: 1 1 1 1 1

Read it in plain English: "As long as count is less than 5, print 1 and increase count by 1."

The fun part: change one thing and predict the output

Change Output Why
Start count = 1 1 1 1 1 runs for 1,2,3,4
Use <= instead of < 1 1 1 1 1 1 runs for 0 to 5
Start count = 5 (nothing) 5 < 5 is false right away
Use > instead of < (nothing) 0 > 5 is false
count + 2 1 1 1 runs for 0, 2, 4
count - 1 infinite loop! count keeps going down, always < 5

That last one is a good lesson: if your loop variable never moves toward the stopping condition, the loop never ends.

Doing this exercise on paper first taught me more than just running the code would have.

Top comments (0)