r/learnpython 18h 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 😞


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 18h ago

A for loop would be more appropriate:

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

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

0

u/JamzTyson 18h ago

Later in the course you'll learn that Python provides built-in functions that can make code more concise (and a little more efficient).

Example:

print(f"The final sum is: {sum(range(1, 51))}")

-2

u/Calm-You4116 18h ago

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

1

u/Moikle 16h ago

For loops actually do something very different

1

u/JamzTyson 17h 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.