Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 2    ❮    Lesson List    ❮    Top Page

❯  2.1  for Loop

2.2 List Comprehension

2.3 Boolean Operators

2.4 if Statement

2.5 Looping if Statement   

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   6m 2s
☷  Interactive readings   5m

Writing Basic for Loop

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.

Writing Multiple Lines inside for 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.

WRITE BETTER CODE
Using Assignment Operator

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!

LEARN FROM ERRORS
IndentationError in for Loop

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.

IndentationError when Unnecessarily Indenting

Adding indentation when it is not needed will cause an error. Deleting the indent will solve this error.

SyntaxError in for Loop

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.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse