4. access by index


I'm trying to do the MONTY thing, but when I do what it says I get:

Traceback (most recent call last):
File "python", line 13, in
IndexError: string index out of range

My code is this:

The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:

| P | Y | T | H | O | N |
0 1 2 3 4 5

So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
fith_letter = "Y"[0-1-2-3-4-5]
y = "Yawn"
print fifth_letter

I don't know what I did wrong.


Ok let me walk you through what this lesson is talking about.

1.) "On line 13, assign the variable fifth_letter equal to the fifth letter of the string "MONTY"."
Each character in a string is assigned a number. This number is called the index. This lesson is all about accessing that index through what we code. We want the fifth letter of Monty to be printed on the screen. To do this we must assign our variable, in this case fifth_letter equal to the fifth letter in Monty. We will accomplish using the index. You are given two examples of this in the example for this lesson.

c = "cats"[0]

As you can see from this example, the person coding is wanting the first letter in cat to appear. Therefore, to get this he or she must equal their variable c to "cats" the word they want to take the letter from and then index it using brackets and the number of that letter in the word. In this case, it is 0. For you see the first letter in each word does not start at 1 but at 0. This is a very common mistake that throws people for a loop. Therefore, to get in this case Y for Monty lets look at it.

So first we need the variable which is fifth_letter. Second, the equal sign. Third, our word which is "MONTY". And finally the number in brackets of which letter we want. Now for the fifth letter in Monty or Y to show we need the number 4 as we count like this in getting y from Monty.

| M| O | N | T | Y |
  0  1   2    3   4

So our final line is going to be fifth_letter = "MONTY" [4]. Now all you need to do is print fifth_letter and it looks like you do that very well! :smiley:


oh ok thanks for your help! :slight_smile:


No problem! Glad to have helped! :smiley: Did that solve what you were stuck on?


I'm still working it out but yeah:grinning:


Ok well just let me know if you need anymore help. I will be consistently on for the next couple of hours so just post back in this discussion if anything is needed! :thumbsup:


Ok I will! I got it finished!:grin:


I understand Y is the fifth letter character in MONTY but the lesson explains we start at 0 in coding language and we need to find the fifth letter in MONTY
How can Y be 5 if 5 doesn't exist


Since the way you count in real life starting from 1 instead 0.
In Python, you start with 0


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.