A variable is a named storage location for a value, such as total or score. Its value can change while the program runs, but its name stays the same. Good names describe what the value means, so a variable named total is easier to read than a name such as x.
A loop repeats a block of instructions while a condition is true, or for a set number of times. Loops are useful when the same step must be applied to many values, such as adding every score in a list.
A function is a named block of instructions that can receive inputs, called parameters, and can return a result. Functions reduce repeated code and make programs easier to test, because the same logic works with different inputs.
Inside your account
What an account adds to the pages you are reading.
Lessons
Topic explanations with worked examples, split into units.
Assignment stores a value in a variable. In many languages a single equals sign means assignment, and a double equals sign means comparison.
A loop needs a starting value, a stopping condition and a change at each step.
A function takes parameters and may return a value.
A variable declared inside a function is usually local to that function.
Clear names make code easier to read and debug.
Example
A loop that adds the numbers from 1 to 5 can be traced by hand. Start with total = 0. For i = 1, total becomes 1. For i = 2, total becomes 3. For i = 3, total becomes 6. For i = 4, total becomes 10. For i = 5, total becomes 15. The final total is 15.
A function double(x) returns x times 2. Calling double(7) gives 14, and calling double(10) gives 20. The same function works for any number that is passed to it.
Common mistakes
Off-by-one errors. A loop that runs from 1 to 5 repeats five times, but a loop from 0 to 5, inclusive, repeats six times.
Forgetting to change the loop variable, which can create an endless loop.
Using a variable before it has been given a value.
Writing a function that prints a result but never returns it, so the calling code cannot use the value.
Summary
Variables store values that can change, loops repeat steps while a condition holds, and functions package reusable logic with inputs and outputs. Tracing a small example by hand, with a clear starting value and stopping rule, is the best way to check how these tools work.
Names let the program and the reader refer to a stored value without knowing its memory location. Clear names also make the purpose of the value easier to understand.
What is an endless loop?
An endless loop is a loop whose stopping condition is never met, so it keeps repeating. It usually happens when the loop variable is never changed, or when the condition is written wrongly.
What is the difference between a parameter and an argument?
A parameter is the name listed in the function definition. An argument is the actual value passed in when the function is called. In double(x), x is the parameter, and 7 in double(7) is the argument.