Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Things That Count Exceptions

Aaron Brown
Aaron Brown
2,551 Points

Index out of range when using float numbers smaller than character length. Why?

Here is my code, which is just like that in the video.

user_string = input("What's your word? ")
user_num = input("What's your number? ")

try:
    our_num = int(user_num)
except: 
    our_num = float(user_num)

if not '.' in user_num:
    print(user_string[our_num])
else:
    ratio = round(len(user_string)*our_num)
    print(user_string[ratio])

Here is the output

aarons_air:TeamTreehouse Aaron$ python3 percent_letter.py
What's your word? Happiness
What's your number? 1.3
Traceback (most recent call last):
  File "percent_letter.py", line 13, in <module>
    print(user_string[ratio])
IndexError: string index out of range
aarons_air:TeamTreehouse Aaron$ 

Any guidance on why I am not getting the correct output would be much appreciated.

Edwin Ty
Edwin Ty
3,940 Points

I had the same issue as well. The thing I spotted was that the float number is restrained to 0-1, which is why the example works in the video.

1 Answer

Michael Norman
PLUS
Michael Norman
Courses Plus Student 9,399 Points

You are getting this error because it is assumed that the float entered will be 0.0 - 1.0, though I can't remember if it was mentioned in the video. When you put 1.3 you are asking to find the character that is 130% through the word.

user_string = "Happiness"
our_num = 1.3

ratio = round(len(user_string)*our_num) # equals: round(9 * 1.3) -> round(11.7) -> 12
print(user_string[ratio])  # user_string[12] - trying to get the character at index 12

As you can see in the comments above "Happiness" is only 9 characters long but you are trying to get the character at index 12 which is ~130% the length of the word. This is why it is saying "string index out of range". The range for this word is 0-9.