Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Shorthand Operator?

I was researching some information on the topic of trial division, and I came across this symbol in Python:

//=

I got this from here where the code in the example says:

n //= p

I can't tell what this is supposed to mean, and my research continues to bring poor results in terms of webpages.

like image 416
nmagerko Avatar asked Oct 16 '11 20:10

nmagerko


3 Answers

// is integer division and the

n //= p

syntax is short for

n = n // p

except the value n is modified directly if it supports this.

like image 125
Jochen Ritzel Avatar answered Sep 25 '22 03:09

Jochen Ritzel


When you see an operator followed by an =, that is performing the operation and then assigning it into the variable. For example, x += 2 means x = x + 2 or add 2 to x.

The // operator specifically does integer devision instead of floating point division. For example, 5 // 4 gives you 1, while 5 / 4 gives you 1.25 (in Python 3).

Therefore, x //= 3 means divide x by 3 (in an integer division fashion), and store the value back into x. It is equivalent to x = x // 3

like image 28
Donald Miner Avatar answered Sep 23 '22 03:09

Donald Miner


// is the floor division operator, therefore //= is simply the inplace floor division operator.

like image 36
Alex Gaynor Avatar answered Sep 24 '22 03:09

Alex Gaynor