There are three examples:

  1. Example: 's' * 3
    Result: 'sss'
  2. Example: 's' * True
    Result: 's'

  3. Example: 's' * 3.7
    Result: TypeError: can't multiply sequence by non-int of type 'float'

Questions:

  1. Why does example 2 return 's'?
  2. Why does Example 3 throw an exception?
  • 2
    1 - most likely True == 1 implicit conversion. 2 - no multiplication by fractional. To the whole does not lead directly. - pavel
  • It turns out that True is cast to 1 type int? Why it happens? - Max
  • @Max, because the internal representation is True == 1, try: True * 3.7 - MaxU
  • one
  • @vadimvaduxa is a good article, but in English ( - Max

1 answer 1

With the error in the third example, everything is obvious - the line cannot be repeated a fractional number of times, so the multiplication of the string is defined only by int.

With the second example, a little more interesting.

Python developers did not begin to make a logical type from scratch, but simply inherited it from int. True is equivalent to one, and False is zero.

Thus, with a logical data type, you can do all the mathematical operations that are defined for an integer type.

 isinstance(True, int) # Выведет: True # То есть логический тип действительно является потомком int 3 + True # Выведет: 4 # То есть True действительно эквивалентен единице 3 / False # Выведет ошибку деления на ноль # То есть False действительно эквивалентно нулю