Lecture
How to Perform Iterations Based on Conditions in Python
In programming, a loop is used to perform the same task repeatedly.
Loops iterate over a series of items, such as lists, tuples, or strings, performing the same task for each item.
These lists, tuples, strings, etc., are referred to as sequences, and each item in a sequence is called an element.
Structure of a for Loop
A for loop starts with the for keyword and specifies a variable that represents each item in the sequence to be iterated over as follows:
Structure of a for Loop
for element in sequence: code_to_repeat <br /> Each item in the sequence is sequentially assigned to the variable `element`, and the `code_to_repeat` is executed. In loops, a colon (`:`) must follow the sequence, and the `code_to_repeat` must be indented. The following `for` loop example assigns each element of the `numbers` list, a sequence of numbers, to the `n` variable in turn and prints `n`. ```python title="for Loop Example" numbers = [1, 2, 3, 4, 5] # Assign each element of the numbers list to the variable n in turn for n in numbers: print(n) # Print the variable n # 1, 2, 3, 4, 5 will be printed on separate lines
Lessons in this chapter · For Loop: Structure and Usage
- 1. How to Perform Iterations Based on Conditions in Python
- 2. Using `for` loops with Lists
- 3. Nested Lists and Nested Loops
- 4. Multiple-choice quiz
- 5. Expanding Sequence Elements with the Spread Operator
- 6. Utilizing for Loops with Dictionaries
- 7. How to Create a Range of Numbers in Python
- 8. Coding Quiz - for Loop
- 9. Multiple-choice quiz
- 10. Fill-in-the-blank quiz
Quiz
0 / 1
What is the correct syntax for iterating over each element in a list using a for loop in Python?
for element in list
for list in element
for element in list:
for list in element:
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help