Home »
Python
Find output of Python programs - 1
This section contains the programs with correct output and explanations in Python; you have to find your output of particular program and match output with the given output.
Submitted by Abhishek Jain, on October 02, 2017
1) Find the output of the following code:
sum = 0
for i in range(12,2,-2):
sum+=i
print sum
Output
40
Explanation
The syntax for the range() method is range(start, stop, step). The for loop starts from 12 and ends at 2 (excluded) while at each step decrement of -2 take place. Thus, sum = 12+10+8+6+4 = 40
2) Find the output of the following code:
n=50
i=5
s=0
while i<n:
s+=i
i+=10
print "i=",i
print "sum=",s
Output
i= 55
sum= 125
Explanation
Variable i act as a counter variable which change its value at each iteration. Starting from 5, each time incremented by 10. The while loop went false when i becomes 55 (which is >n(50)) makes sum = 125.
3) Find the output of the following code:
List=[1,6,8,4,5]
print List[-4:]
Output
[6, 8, 4, 5]
Explanation
Negative index traverse the List in reverse order. Here, List[-4:] represent elements from (size-4+1)=(5-4+1) i.e, 2nd element to the last element of the list.
4) How many times are the following loops executed?
i=100
while(i<=200):
print i
i+=20
Output
6
Explanation
Initially i=100 and keep incrementing by 20, where while loop breaks when i becomes 220 (which is >=200).
5) Find the output of the following code:
L=[100,200,300,400,500]
L1=L[2:4]
print L1
L2=L[1:5]
print L2
L2.extend(L1)
print L2
Output
[300, 400]
[200, 300, 400, 500]
[200, 300, 400, 500, 300, 400]
Explanation
Due to 1st step, now L1 comprises 3rd and 4th element of the list L. While list L2 contains all the elements of list L except the last one. In last line of code, L2 extends L1 i.e., all the elements of L1 will appended in L2.
6) Predict the behavior of the code:
List=list("String")
print List
Output
['S', 't', 'r', 'i', 'n', 'g']
Explanation
list() method treat string as a sequence of characters. Each character of the string "String" behaves as a separate element for the list.