-2

I'm new to programming, and obviously I can easily run a program to get the answer, but I want to get a clearer and better understanding of why this code runs "dessert". I understand len(s) is the length of the number, but what about the three numbers "-1, 0 -1"? Can I get a detailed explanation of why this prints dessert?

s = "stressed"

for i in range(len(s)-1, 0, -1):
    print(s[i], end = " ")
Nicole Arnone
  • 37
  • 1
  • 3
  • 2
    There's a documentation for [range](https://docs.python.org/3/library/functions.html#func-range). – Matthias Nov 24 '14 at 16:52

4 Answers4

1

The code creates a range that counts down. Starting at len(s) - 1 (so 7, stressed is 8 characters long), it'll count down to 1 (the end point is not included). In other words, you are giving range() three arguments, len(s) - 1 is one argument, 0 is the second and -1 is the third, and they represent the start, stop and step arguments. See the range() type documentation.

The code then uses those values to index s; s[7] is the last character in the string, d, then s[6] is the one-but last character e, etc.

Breaking this down to the components in an interactive session:

>>> s = "stressed"
>>> len(s)
8
>>> len(s) - 1
7
>>> list(range(7, 0, -1))
[7, 6, 5, 4, 3, 2, 1]
>>> s[7]
'd'
>>> s[6]
'e'
>>> s[1]
't'

If you wanted the code to print out desserts (with the s at the end) then you need to adjust the range() to loop up to -1:

for i in range(len(s) - 1, -1, -1):
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

s t r e s s e d

0 1 2 3 4 5 6 7

range function : range(start, stop, step)

len(s) = 8

len(s-1)= 7

the loop starts at 7 stops at 0 and counts(steps) bacwards by 1 (-1) so , the loop prints

7 6 5 4 3 2 1

d e s s e r t

0

It's all about range().

It's all discussed here.

It can be used in three ways;

range(stop)
range(start, stop)
range(start, stop, step)

Where in the first case, it will give [1, 2, 3, ... stop-1], in the second case [start, start+1, start+2, ... stop-1], and in the third case [start, start+step, start+2*step, ...stop-step].

The thing to note here is that the range you get is [start, stop). Where standard interval notation has been used.

The other thing to note here is that step can be negative, which is what you have in your example.

will
  • 10,260
  • 6
  • 46
  • 69
0
range(len(s)-1, 0, -1)
reange(start_index, to_end_index, is_increment or is_decrement)

You call a loop with its start index, then tell it to traverse to end index and lastly increase the index or decrease the index

range(len(s)-1 *calculate the lengthof array (string), 0 *end point of traversing, -1 decrement the index)

If you use

range(0, len(s),1)

The loop will start from 0 index and traverse till last index with 1 index increment

Sk Borhan Uddin
  • 813
  • 1
  • 9
  • 19