Computer Science
Assuming words is a valid list of words, the program below tries to print the list in reverse. Does it have an error ? If so, why ? (Hint. There are two problems with the code.)
for i in range(len(words), 0, -1):
print(words[i], end=' ')
Answer
There are two issue in range(len(words), 0, -1)
:
- The start index
len(words)
is invalid for the listwords
as it will have indexes from 0 tolen(words) - 1
. - The end index being 0 means that the last element of the list is missed as the list will be iterated till index 1 only.
The corrected python code is :
for i in range(len(words)-1, -1, -1):
print(words[i], end=' ')
Related Questions
Find the errors. State reasons.
t = 'hello' t[0] = "H"
Find the errors. State reasons.
for Name in [Amar, Shveta, Parag] IF Name[0] = 'S': print(Name)
What would be the output of following code if
ntpl = ("Hello", "Nita", "How's", "life?") (a, b, c, d) = ntpl print ("a is:", a) print ("b is:", b) print ("c is:", c) print ("d is:", d) ntpl = (a, b, c, d) print(ntpl[0][0]+ntpl[1][1], ntpl[1])
Predict the output.
tuple_a = 'a', 'b' tuple_b = ('a', 'b') print (tuple_a == tuple_b)