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")
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
Related Questions
Find the errors in the code given below and correct the code:
if n == 0 print ("zero") elif : n == 1 print ("one") elif n == 2: print ("two") else n == 3: print ("three")
What is following code doing? What would it print for input as 3?
n = int(input( "Enter an integer:" )) if n < 1 : print ("invalid value") else : for i in range(1, n + 1): print (i * i)
Rewrite the following code fragment using for loop:
i = 100 while (i > 0) : print (i) i -= 3
Rewrite the following code fragment using for loop:
while num > 0 : print (num % 10) num = num/10