KnowledgeBoat Logo

Computer Science

How are following two code fragments different from one another? Also, predict the output of the following code fragments :

(a)

n = int(input( "Enter an integer:" ))
if n > 0 :
    for a in range(1, n + n ) :
        print (a / (n/2))
    else :
        print ("Now quiting")

(b)

n = int(input("Enter an integer:"))
if n > 0 :
    for a in range(1, n + n) :
        print (a / (n/2))
else :
    print ("Now quiting")

Python

Python Control Flow

22 Likes

Answer

In part (a) code, the else clause is part of the loop i.e. it is a loop else clause that will be executed when the loop terminates normally. In part (b) code, the else clause is part of the if statement i.e. it is an if-else clause. It won't be executed if the user gives a greater than 0 input for n.

Output of part a:

Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335
Now quiting

Output of part b:

Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335

Answered By

12 Likes


Related Questions