There are a number of simple errors that beginners frequently make in many different languages. Examples include:
- Using a loop to calculate a result, and putting the
print
statement to show the result inside the loop instead of after it's done. - Initializing an accumulator variable in the loop instead of before it.
- When using a variable that should persist state between calls to a function, declaring it inside the function instead of globally.
- (variation on #3) Re-declaring a variable from an outer scope in an inner scope, rather than just assigning it.
Questions due to errors like this come up numerous times every day (how to print sum of numbers between any given numbers using loop python is a recent example of #1). But searching for previous questions to use as a duplicate is difficult, since there's no search criteria that's likely to find them.
I feel like we could have a language-agnostic, FAQ-style community question that demonstrates all these errors along with the (fairly simple) fixes. Then we could close most of these questions as duplicates of this question. The title could be something like "What are some common logic errors and how can they be fixed?"
Would this be reasonable to start?
for (int i = 0; i <= arrayLength; i++)
and thus go out of bounds of the array indexes. I feel it's in the same vein of what you propose, so we have a precedent.=
and==
operators and what is===
? (Single, double, and triple equals) for the good oldif(variable = value)
.