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 trialFrancis Neal
528 PointsWhy // and not just / in the (num_of_char // 2) line?
Hi there,
In the line:
result = text + "!" * (num_of_char // 2)
Why do we need // and not just /? Just / returns the error:
result = text + "!" * (num_of_char / 2)
TypeError: can't multiply sequence by non-int of type 'float'
Thanks
Francis :-)
2 Answers
Steven Parker
231,275 PointsThe string (sequence) multiplying operation only works with an integer repeat count, but the normal division operator (/) always returns a float result which is not compatible.
Using the integer division operator instead (//) returns an integer result.
You could also use "int(num_of_char / 2)
".
Martin Luckett
32,591 Points(Originally added as comment rather than an answer - oops)
// is the floor division operator which is also sometimes called integer division and returns an integer whereas / may return a float (non-integer).
For example, 5 / 2 will return 2.5 (a float) where 5 // 2 will return 2 (an integer).
Multiplying text requires an integer as, for example, text plus "!" times 2.5 does not make sense.
It is a TypeError because the multiplication of sequences requires integers and using a single / can give a float.