0

What is the output this code?

str=[1,2,3] if 0 and 1: print (str[2]) elif 1 or 0: str = str[::-1] print(str[2]) This answer is 3. Why?

23rd Jun 2017, 1:57 PM
Johnny.J
4 Answers
+ 1
Paste this code in an IDE and you'll find the answer is 1. This is because the if statement is false, and the elif statement is true. The string is reversed, and the value at index 2 is now 1. (The new string is 3,2,1).
23rd Jun 2017, 2:02 PM
Frederik Bussler
Frederik Bussler - avatar
0
I got it. If -1 of line 5 changes to 1, this answer is 3, right?
23rd Jun 2017, 2:08 PM
Johnny.J
0
Correct Johnny, because it'll loop through str forwards, and str will still be [1,2,3], so index 2 will yield 3.
23rd Jun 2017, 2:10 PM
Frederik Bussler
Frederik Bussler - avatar
0
Thank you for your comments! I understand all very well.
23rd Jun 2017, 2:14 PM
Johnny.J