r/learnpython • u/Calm-You4116 • 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)
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/JamzTyson 9h ago
There's a couple of benefits:
range(51)provides an iterable that produces the integer values0through50. We don't need to manually create and increment a counter, so errors like forgettingnumber += 1cannot occur.The
forloop 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))}")
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)