NCERT Computer Science Class #11 – Chapter #6 Solutions – Q #2

Chapter 6 – Flow of Control

NCERT Computer Science Class #11 – Chapter #6 Solutions

Q #2: What is the purpose of range() function? Give one example.

The range() function in Python is used to generate a sequence of numbers. It is particularly useful for iterating over a sequence in loops, such as for loops. The function can take one to three arguments: start, stop, and step.

Purpose of range()

  • Default Behavior: When called with a single argument, range(stop), it generates numbers starting from 0 up to, but not including, the specified stop value. For example, range(5) produces the sequence 0, 1, 2, 3, 4.
  • Custom Start and Stop: When two arguments are provided, range(start, stop), it generates numbers starting from start up to (but not including) stop. For instance, range(2, 5) results in 2, 3, 4.
  • Custom Step Size: With three arguments, range(start, stop, step), you can specify the increment between each number in the sequence. For example, range(0, 10, 2) yields 0, 2, 4, 6, 8.

Example

Here’s a simple example demonstrating the use of the range() function in a loop:

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

Output:

0
1
2
3
4

Example 1: Specifying Start and Stop

# Using range() with start and stop
for i in range(3, 8):
    print(i)

Output

3
4
5
6
7

Example 2: Specifying Step Size

# Using range() with start, stop, and step
for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

Example 3: Counting Down

# Using range() to count down
for i in range(5, 0, -1):
    print(i)

Output:

5
4
3
2
1

Example 4: Creating a List of Numbers

# Creating a list of numbers using range()
numbers = list(range(1, 11))
print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 5: Summing Numbers

# Summing numbers from 1 to 100 using range()
total = sum(range(1, 101))
print(total)

Output:

5050

Example 6: Generating a Multiplication Table

# Generating a multiplication table for 5
number = 5
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

NCERT Computer Science Chapter 6 Solutions Q 1

Posts created 29

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top