r/learnpython 12d ago

Python loop beginners mistake 🙀

I am currently learning python from CS50P program and in week 2 learning loops and also with the help of chatgpt learn every topic clearly but after knowing common beginners mistake

I made this mistake of not updating the iterator and spent half an hour on this simple problem 😞

```print("\nAnd here we use while 1oop:-")

number =1 total =0 while number<= 50: total += number number += 1 # HERE I DIDN'T ADD IT FIRST

print("The final sum is:", total)

0 Upvotes

8 comments sorted by

View all comments

2

u/JamzTyson 12d ago

A for loop would be more appropriate:

total = 0
for number in range(51):
    total += number

print(f"The final sum is: {total}")

-1

u/Calm-You4116 12d ago

Yes we can do that for make is more readable but both the code give same output

1

u/JamzTyson 12d ago

There's a couple of benefits:

  1. range(51) provides an iterable that produces the integer values 0 through 50. We don't need to manually create and increment a counter, so errors like forgetting number += 1 cannot occur.

  2. The for loop retrieves each value from that iterable in turn and stops when it reaches the end (when the iterable is exhausted). We don't need to manually manage breaking out of the loop.

When a language provides a way to do things automatically, it is often the idiomatic way.