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 trialLorrian Landicho
278 PointsCoerce "len" to become integer
print(int(len(text))/2)
No error came back , but the result came back as a float. Please explain why; thanks
2 Answers
Grigorij Schleifer
10,365 PointsHi Lorrian, the operator / returns a float value if one of the arguments is a float. The real floor division operator is “//”. It returns floor value for both integer and floating point arguments. Check this link.
See the example:
>>> type(int(len("I am a string"))//2)
<class 'int'>
>>> type(int(len("I am a string"))/2)
<class 'float'>
Does it make sense?
Marcus Grant
Courses Plus Student 2,546 PointsJust to add on to Grigorijs' great example.
Remember your Order of Operations (PEDMAS or BODMAS or BIDMAS).
Your code: print(int(len("Hello"))/2)
Reading your code from the inside out (because anything inside brackets is calculated first):
- Get length of "Hello" (5)
- Convert the length of "Hello" to an int value (5)
- Divide the int value by 2 which results in a float value (2.5)
- Print the float value. (2.5)
My change: print(int(len("Hello")/2))
What my change does:
- Get length of "Hello" (5)
- Divide length of "Hello" by 2 which is a float value. (2.5)
- Convert the float value to an int which drops the decimal value. (2)
- Prints the int value. (2)
Hope this helps too.
Grigorij Schleifer
10,365 PointsGrigorij Schleifer
10,365 PointsHere a nice stack overflow post