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

Help with percent_letter.py

I don't understand what is wrong with my line of code on line 10 of the percent_letter.py For some reason my code for the previous line doesn't match the colors on Kenneth's screen the "not" and "in" are not highlighted in another color, they're black. Is that the reason why it isn't working?

6 Answers

Stone Preston
Stone Preston
42,016 Points

you have 2 typos that are most likely causing the issue

except: 
  out_num = float(user_num)

should be

except: 
  our_num = float(user_num)

and

ratio = round(len(user_string)*out_num)

should be

ratio = round(len(user_string)*our_num)

when you have syntax errors in your code the editor wont highlight code, it wont indent properly, it just doesnt work like it does when your code is correct. so if you are ever writing your code and notice all of the sudden it wont indent/highlight correctly go back and check yourself.

Stone Preston
Stone Preston
42,016 Points

oh you need to use our_num for the index not user_num.

if not '.' in user_num: 
 print(user_string[user_num])

should be

if not '.' in user_num: 
 print(user_string[our_num])

the number the user entered is a string. we convert it to an int and store it in the variable our_num so we can use that to index the string the user entered (since strings are just lists of characters)

how do i do that?

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

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

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

The error is: Traceback (most recent call lat): File "percent _letter.pu", line 10, in <module> print(user_string[user_num]) TypeError: string indices must be integers

11 months late but I figured out the issue. Keep in mind this is Python 2.7.6.

ratio = round(len(user_string)*out_num)

It's rounding the number but storing that number as a float. Convert it to an integer and it works.

Ex.

ratio = int(round(len(user_string)*out_num))

Not sure if Python 3 works differently.