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 |