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 Functions and Looping Functions

Lorrian Landicho
Lorrian Landicho
278 Points

Coerce "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
Grigorij Schleifer
10,365 Points

Hi 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
PLUS
Marcus Grant
Courses Plus Student 2,546 Points

Just 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):

  1. Get length of "Hello" (5)
  2. Convert the length of "Hello" to an int value (5)
  3. Divide the int value by 2 which results in a float value (2.5)
  4. Print the float value. (2.5)

My change: print(int(len("Hello")/2))

What my change does:

  1. Get length of "Hello" (5)
  2. Divide length of "Hello" by 2 which is a float value. (2.5)
  3. Convert the float value to an int which drops the decimal value. (2)
  4. Prints the int value. (2)

Hope this helps too.