Loops: for and while
In programming, we often need to repeat actions, such as printing items, summing values, or checking conditions. Loops let us do this efficiently without writing the same code multiple times.
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 set of items you want to process. - Use a
whileloop when the number of repetitions depends on a condition that may change.
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
Code Editor
Run
Generate
Execution Result