Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping Functions

Francis Neal
Francis Neal
528 Points

Why // 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'


Francis :-)

2 Answers

Steven Parker
Steven Parker
216,012 Points

The 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
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.