Which function is commonly used with for loops to generate a sequence of numbers?

Which function is commonly used with for loops to generate a sequence of numbers?

a) len()
b) range()
c) enumerate()
d) zip()

Answer:

b) range()

Explanation:

The range() function in Python is commonly used with for loops to generate a sequence of numbers. This function returns an immutable sequence of numbers, starting from 0 by default, and increments by 1 (unless specified otherwise).

for i in range(5):
    print(i)  # Prints numbers from 0 to 4

The range() function is versatile, allowing you to specify the start, stop, and step values for generating sequences. It’s widely used for iterating over a specific number of times or when you need to access indices in a loop.

Using range() in for loops is a fundamental aspect of Python programming, especially when working with numerical data or performing tasks a fixed number of times.

Scroll to Top