Home > Software design >  python : meaning of -----if not (p%q):
python : meaning of -----if not (p%q):

Time:11-24

this is code i got from paper,

I want to know meaning of

if not (p%q)

x = 0
p = 2
while(p<7):
  q=2
  while(q<p):
    if not (p%q):q=p
    q =1
  if(q>p):x =p
  p =1
print(x)`

CodePudding user response:

It is essentially saying if True (If the modulo == 0). The modulo sign (%) gets the remainder of a division. The modulo operator(%) is considered an arithmetic operation. So since it is doing 2/2, we get a modulo of 0. Now the statement is if not 0:.

That being said, there are truthy and falsy values in Python:

Values that evaluate to False are considered Falsy. Values that evaluate to True are considered Truthy.

Some truthy values include:

  • Non-empty sequences or collections

  • Numeric values that are not zero.

Some falsy values include:

  • Zero of any numeric type.
  • Empty sequences or collections
  • None and False

So the code now translates if not False: (If the modulo != 0), which is the same as if True (If the modulo == 0).

CodePudding user response:

The condition not (p % q) is equivalent to p % q == 0.

For numbers, zero is "falsy" and all others are "truthy": https://docs.python.org/3/library/stdtypes.html#truth. Therefore, we have

"p % q == 0" iff (i.e., if and only if) "p % q is False" iff "not (p % q) is True".

Therefore, if p % q == 0: is equivalent to if not (p % q) is True:, which is in turn equivalent to if not (p % q):, since is True part can be omitted.

  • Related