A: A for loop in Python is used to repeat a block of code a specific number of times. A:The range() function defines how many times the loop iterates. A: The default starting value is 0. When you write for i in range(4), Python generates the values 0, 1, 2, and 3 — four iterations in total. A: A for loop is used when you know in advance how many times you want to repeat something. A: Yes. Use a negative step value in range(). For example, range(5, 0, -1) counts from 5 down to 1.
Frequently Asked Questions
Q: What is a for loop in Python?
It uses the range() function to control how many times the loop runs.
For example, range(5) will repeat the loop 5 times, with the counter taking values 0, 1, 2, 3, and 4.
Q: What does range() do in a Python for loop?
It can take one argument (end value), two arguments (start and end), or three arguments (start, end, and step).
For example, range(2, 10, 2) starts at 2, ends before 10, and increments by 2 each time.
What is the default starting value of a for loop in Python?
What is the difference between a for loop and a while loop in Python?
A while loop runs as long as a condition remains true, which is better when the number of repetitions is not known in advance.
Q: Can a for loop count backwards in Python?