What is the expected output of the following snippet?
What is the expected output of the following snippet?
B
Given answer, B, is correct. But keep in mind too that even if the 'for' statement is corrected, the string is immutable, so assigning a new value to s[i] will fail with "'str' object does not support item assignment. HTH
String is immutable
>>> s="abc" >>> for s in len(s): ... s[i] = s[i].upper() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
strings can actually be modified by this type of loop. But the loop itself doesn't work, because it's just one number, 3. If it was iterable, it would have worked. Try running this: s='abc' for i in s: s=s.upper() print(s) s is iterable, so the result is 'ABC'
It causes an exception because the string s is imutable so attempting to assign to s[i] will fail, however s[i].upper() will succesed
should be for i in range(len... B. The code will cause a runtime exception
[TypeError: 'int' object is not iterable] is returned because len(s) is an int - you can't iterate an int - it's not a collection data type.
Even if the code were s="abc" for i in range(len(s)): >>>>s[i] = s[i].upper() print(s) it would still throw error as below: Traceback (most recent call last): File "<string>", line 5, in <module> TypeError: 'str' object does not support item assignment which was my initial thought
Yes, Type Error. Answer is B