What Is the Output of This python Code?
Question :
x = "Python"
print(x[::-1])
Options :
A) Python
B) nohtyP
C) Pnohty
D) Error
Correct answer :
B) nohtyP
Explanation :
Step 1 - Creating the string
x = "Python"
A variable x stores the string: :
Python
A string in python is a sequence of characters.
Characters in the string :
P y t h o n
Step 2 - understanding string index
Every character in a string has an index position.
Index : 0 1 2 3 4 5
Value : P y t h o n
Meaning :
x[0] → P
x[1] → y
x[2] → t
x[3] → h
x[4] → o
x[5] → n
Python also supports negative indexing.
Index : -6 -5 -4 -3 -2 -1
Value : P y t h o n
Example :
x[-1] → n
x[-2] → o
Step 3 - understanding slicing
Python allows extracting parts of string using slicing.
General syntax :
string[start : end : step]
Meaning :
Start → Where slicing begins
end → Where slicing stops
step → How many positions to move
Example :
x[0:3] → Pyt
Because it takes characters form index 0 to index 2.
Step 4 - Understanding [: : -1]
The code uses :
x[::-1]
This means :
start → default (end of string)
end → default (beginning of string)
step → -1
The step -1 tells python to move backwards.
So python reads the string form right to left.
Step 5 - Reversing the string
Original string :
Python
Reading backwards :
n o h t y P
So the reversed string becomes :
nohtyP
Final output :
nohtyP
Key points :
[::-1] is a common python trick to reverse strings
Strings supports indexing and slicing
A negative step (-1) reverses the order
Works for string , Lists and tuples
Example :
[1,2,3] [: : -1]
Output :
[3,2,1]
Practice daily python coding challenges to improve your programming and logical thinking skills.
Happy coding ❤️

No comments:
Post a Comment