What will be the output of the following Python code?

s = "Hello World"

t = s.count("o", 0, 5)

print(t)

A) 0

B) 1

C) 2

D) 3

Answer:

Answer by student

B) 1

Detailed answer by teachoo

-lock-

In this question, we are using the built-in method count() on a string object. The syntax of this method is:

string.count(substring, start, end)

Where,

  • string is the original string
  • substring is the substring to be counted
  • start and end are optional parameters that specify the range of indices to search within the string. 
  • The method returns the number of occurrences of the substring in the string within the specified range.
  • Now that we know this concept, we can proceed to find out the output of the code. We will follow these steps:
    • First, we will assign the value “Hello World” to the variable s using the statement s = "Hello World" .
    • Next, we will call the method count() on s with the arguments “o”, 0, and 5 using the statement t = s.count("o", 0, 5) . This means we want to count how many times “o” appears in s from index 0 to index 4 (excluding index 5).
    • To do this, we will look at each character of s from index 0 to index 4 and compare it with “o”. The characters and their indices are:

Index

Character

0

H

1

e

2

l

3

l

4

o

 

We can see that only one character matches with “o”, which is at index 4.

  • Therefore, the method will return 1 as the result and assign it to t.
  • Finally, we will display the value of t using the statement print(t) . This will print 1 on the screen.
  • Therefore, option B) is the correct answer.

So, the correct answer is B) 1.

-endlock-

Remove Ads Share on WhatsApp
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.