Lecture
Loops: for and while
In programming, we often need to repeat actions — such as printing items, summing values, or checking conditions. Loops allow us to do this efficiently without rewriting the same code.
Python provides two main types of loops: for and while.
for Loops
A for loop is used when you want to go through each item in a sequence, such as a list, string, or range of numbers.
For Loop
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit)
Explanation
fruitsis a list.- The variable
fruittakes one value from the list in each loop. - The loop prints a sentence using that value.
- This repeats three times, once for each fruit.
while Loops
A while loop runs as long as a condition is true.
While Loop
count = 1 while count <= 3: print("Count is:", count) count += 1
Explanation
- The loop starts with
count = 1. - It checks the condition
count <= 3. If it is true, the block runs. - After each loop,
countincreases by 1. - When
countbecomes 4, the condition is false and the loop stops.
When to Use Each
- Use a
forloop when you already know the collection of items you want to process. - Use a
whileloop when the number of repetitions depends on a condition that can change over time.
Previous lessonConditional Statements (if, elif, else)Next lessonControl Flow & Data Structures Recap
Lessons in this chapter · Python Programming Review
- 1. Variables and Data Types
- 2. Expressions and Arithmetic
- 3. String Operations
- 4. Lists in Python
- 5. List Methods and Slicing
- 6. Tuples and Sets
- 7. Dictionaries - Keys and Values
- 8. Dictionary Methods and Nesting
- 9. Conditional Statements (if, elif, else)
- 10. Loops - for and while
- 11. Control Flow & Data Structures Recap
- 12. Multiple-choice quiz
- 13. Loop Controls (break, continue, pass)
- 14. Functions - Defining and Calling
- 15. Function Arguments and Return Values
- 16. Variable Scope and Nested Functions
- 17. Exception Handling with try/except
- 18. File Reading and Writing
- 19. CSV File Parsing
- 20. Using Built-in Modules (math, random, datetime)
- 21. Importing External Modules
- 22. Fill-in-the-blank quiz
Quiz
0 / 1
In Python, a while loop is useful when you need to iterate over a known sequence of items.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help