Look at the following two code snippets where each code counts number of letters ‘f’ and ‘s’ in a sentence:

// code 1                    //code 2

:                            :

if (c ==’f’):                if (c ==’f’):

nf++                            nf++

if (c==’s’):               elif (c==’s’):

ns++                           ns++

What is the difference between the two codes given above.

 

Answer:

Code 1

Code 2

There are two if statements used, and each one is tested separately. Whether the result of the first is true or false , the second will always run.

if-elif statement is used. In this, if the first  condition becomes true then the program will  not check the latter conditions. 

Takes more time to process

More efficient

 

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo