Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop Help
#1
Lets just assume the code below can't be altered. Can someone please explain to me the (last_index, -1, -1): part? I understand for i in range (last_index but I am unsure about the additional -1 -1). Thank you in advance



text = input('Line: ')
last_index = len(text) - 1
backwards_text = ''
for i in range(last_index, -1, -1):
  backwards_text = backwards_text + text[i]
print(backwards_text)
Reply
#2
First parameter in a range is the start of an iteration, second is the end and third is a step, so in your example:
* beginning is a length of text-1
* end is on 0 (step before -1)
* step is -1

e.g.
In [1]: for i in range(20, -1, -1):
   ...:     print i
   ...:     
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Reply
#3
(Aug-09-2017, 11:56 AM)tjmck2 Wrote: Lets just assume the code below can't be altered. Can someone please explain to me the (last_index, -1, -1): part?
Should not use it,there is reversed() which most understand without explaining.
text = input('Line: ')
backwards_text = ''
for i in reversed(text):
    backwards_text += i

print(backwards_text)
There is also [::-1].
>>> s = 'hello'
>>> s[::-1]
'olleh'
Reply
#4
Thanks everyone!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020