Lesson 2 ❮ Lesson List ❮ Top Page
❯ 2.1 for Loop
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 6m 2s
☷ Interactive readings 5m
In Python, you can perform a for loop simply by providing a list and a temporary variable. The for loop will take an element from the list one by one to process.
After that, you just need to indent (press tab) the part of the code you want to loop.
You can write as many lines as you like in the for loop. Every indented line after for number in numbers: is contained inside that loop.
You can also loop through the list items by referring to their index number.
Assignment operators such as +=, -=, *=, and /= can make your for loop shorter and easier to read. This is useful for making summation for example.
The operators += and -= also work for adding/reducing characters in a string. Try it!
Sometimes people forget to put indent after the for statement.
The error will occur on line 3 with the type of error IndentationError. To fix this error, we simply add indentation at the beginning of line 3.
Adding indentation when it is not needed will cause an error. Deleting the indent will solve this error.
The colon (:) and the word in are fundamental parts of for loop.
The example will return SyntaxError, since Python doesn't know what to do. To resolve this error, you can add the colon ( : ) at the end of line 3.