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

.75 * 5 = 3.75, rounded should yield 4, or "i" instead of "c"?

In the first float example, the user_num provided is .75; by my math, .75 * 5 = 3.75, rounded up should yield 4, or in this case the letter "i" instead of "c"?

I feel like I am a complete dunce who missing something very rudimentary.

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Troy, you're no dunce, just human. The indexing on strings is 0-based. So while 0.75 * 5 does round to 4, the index 4 points to the 5th character in a 5-character string. It can take a bit to get used to 0-based indexing.

Using ipython to demonstrate:

In [6]: string = 'magic'

In [7]: string[0]
Out[7]: 'm'

In [8]: string[1]
Out[8]: 'a'

In [10]: string[2]
Out[10]: 'g'

In [11]: string[3]
Out[11]: 'i'

In [12]: string[4]
Out[12]: 'c'

In [13]: string[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-ceafbb581253> in <module>()
----> 1 string[5]

IndexError: string index out of range
Nick Kihfogd
PLUS
Nick Kihfogd
Courses Plus Student 275 Points

So, then if we were entered let's say .99 instead of .75, it would be rounded into 5 and we would get an exception in our code because we don't have such index in our variable? If so, it's mean the code has a logic error and we must decrease the length() value by 1 to achieve correct results?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Correct! Similarly, if you asked the user for the offset integer instead of a percent. You will find subtracting 1 is common to translate from human input to 0-based program counting.

Oh my goodness - I forgot this small but crucially important detail. Thank you, I feel much better now!