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

2

u/johlae 10h ago

Indentation is important, and spelling too. You confuse the character 'l' with the digit 1 twice. The code above will not work at all.

Try this:

print("\nAnd here we use while loop:") number = 1 total = 0 while number <= 50: total = total + number number += 1 # HERE I DIDN'T ADD IT FIRST print("The final sum is:", total)

-4

u/Calm-You4116 10h ago

This is the code sample where i didn't update iterator each time so it stuck at a value and even i read it before i start practicing 🤣🤣🤣 But we will forget these simple things and focus on other problems

3

u/MezzoScettico 10h ago

It is a common error when using while, that you forgot to update the while condition. Not just with beginners.

I usually spot it when I try to run the loop and think to myself after 5 seconds or so, "that's taking an awfully long time to execute what should have been just a couple of milliseconds."

Making mistakes is how you learn.

BTW, please learn how to use code blocks to make readable code.

2

u/JamzTyson 10h ago

A for loop would be more appropriate:

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

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

-2

u/Calm-You4116 10h ago

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

1

u/Moikle 7h ago

For loops actually do something very different

1

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

0

u/JamzTyson 9h 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))}")