while True:
data = input()
if data == 'Done' or data == 'done' or data == 'd':
break
rev = ''
for ch in data:
rev = ch + rev
print(rev)
Asked
Active
Viewed 193 times
-3
-
1`''` is a string. – 12944qwerty May 04 '21 at 02:56
-
You mean, what this expression `rev = ''` actually do? – Franco Morero May 04 '21 at 02:57
-
1It creates a variable named `rev` and assigns it the value of an empty string. – John Gordon May 04 '21 at 03:01
-
You should try 1) removing it to see what happens and why it's needed, 2) `print(rev)` on every iteration to see what the for loop is doing (building the string one character at a time). – Gino Mempin May 04 '21 at 03:04
-
1Related: [Reversing a string in Python using a loop?](https://stackoverflow.com/a/41322353/2745495) – Gino Mempin May 04 '21 at 03:09
1 Answers
2
Based on the code, it is correct the rev
variable acts as reverse of the input.
given this example:
data
is 'hello'
We start the rev
variable as an empty string ''
and we iterate the data string character by character (ch
) and inside the loop we made this operation we prepend the character to the current rev
variable:
So, with the hello
example:
1st iteration: rev
= ch
(h) + rev
('') -> rev now is 'h'
2nd iteration: rev
= ch
(e) + rev
('h') -> rev now is 'eh'
3rd iteration: rev
= ch
(l) + rev
('eh') -> rev now is 'leh'
4th iteration: rev
= ch
(l) + rev
('leh') -> rev now is 'lleh'
5th iteration: rev
= ch
(o) + rev
('lle') -> rev now is 'olleh'

soloidx
- 729
- 6
- 12