Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (Retired) Things That Count Exceptions

Kate Petry
PLUS
Kate Petry
Courses Plus Student 9,432 Points

I'm getting an error after I enter my number that indicates string index is out of range

I have reviewed my code and it looks like what Kenneth has. When I run the code it asked for my word and my number. After I enter the number I get an error that says string index is out of range. I am having trouble understanding why. Here is the code I have.

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])

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

What string and number are you entering?

Kate Petry
PLUS
Kate Petry
Courses Plus Student 9,432 Points

I tried my name as the string, kate, and for the number I tried 44

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

"kate" doesn't have 44 characters in it, though, so doing "kate"[44] will give the error that you described (index is out of range). Try "kate" and 0, 1, 2, or 3.

Kate Petry
PLUS
Kate Petry
Courses Plus Student 9,432 Points

Thank you. I misunderstood the concept of the video. Rewatching again.