Eugene Pashkevich
Eugene Pashkevich

Reputation: 7

what is "size - 1" argument in this loop?

word = input("Enter a word: ")
print("Original String is: ", word)

size = len(word)

print("Prnting only even index chars")
for i in range(0, size - 1, 2):
    print("index[", i, "]", word[i])

I need to understand whether "size - 1" was a subtraction or something else.

I've tried to replace "size - 1" with just "8" and got the same answer. Because the word has 8 characters.

Upvotes: -1

Views: 44

Answers (2)

hualong1009
hualong1009

Reputation: 1

size - 1 is used to ensure that the loop does not include the last character, which is important for both odd and even lengths of the string. You can replace size - 1 with 8 in the context of an 8-character string, but it is generally better to use size - 1 to make the code more flexible and adaptable to strings of different lengths.

Upvotes: -1

mpivet-p
mpivet-p

Reputation: 244

In Python (as in most programming languages), indexes start at 0.

In your case, if the user type "Hello World!", word[0] will contain the character "H", word[1] = "e", word[2] = "l" so on and so forth.

When iterating over each character, the last index accessed will be size - 1, since size represents the total number of characters in the string, and indexing starts from 0.

Upvotes: -1

Related Questions