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 trialTroy Douglas
1,069 Points.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
Treehouse Moderator 68,441 PointsTroy, 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
Courses Plus Student 275 PointsSo, 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
Treehouse Moderator 68,441 PointsCorrect! 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.
Troy Douglas
1,069 PointsOh my goodness - I forgot this small but crucially important detail. Thank you, I feel much better now!