Search code examples
pythonsyntaxmodulofloor-division

What do operations n % 2 == 1 and n //= 2 do in Python?


Can someone explain the semantics of

n % 2 == 1

and

n //= 2

As I understood n % 2 == 1 checks if the remainder of the division of n by 2 is 1.

What about n //= 2? Is this a floor division? But of what? n divided by 2?


Solution

  • n % 2 == 1 means to return True if the remainder of n / 2 equals to one, the same as checking if n is an odd number.

    So if n equals to 6, the above expression will return False. If n equals to 9, it will return True.

    n //= 2 means to redefine the n variable, but assigning the original value with the floor division of 2 calculated into it.

    So if n equals to 6, the above expression will change its value to 3. If n equals to 9, it will change its value to 4.