0

I have searched but it looks like this is almost too basic to have been posted prior to this. I am starting to learn Python and I have been given an example to write. One thing I don't understand about it is how the % works in this specific example below:

print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

I have used basic order of operations to break it down a little bit

(3 + 2 + 1 - 5) + (4 % 2) - (1 / 4) + 6
       1        + (4 % 2) -   .25   + 6
       1        + (4 % 2) -      6.25

Where I am stuck at is how (4 % 2) works. Reading the example further on the final result is 7 but I am not seeing how it comes to this. I think the issue is how I am reading it in my head. Any help would be greatly appreciated.

BrianStoiber
  • 45
  • 1
  • 1
  • 6

2 Answers2

0

The % i.e modulo operator gives the remainder of the division.

e.g.

>>> 5%3
2
>>> 15%3
0
>>> 

The / division operator works like:

Integer value divided by integer value give an integer not float(1/4 = 0.25)

>>> 1/4
0
>>> 1.0/4
0.25
>>> 1/4.0
0.25
>>> 1.0/4.0
0.25
>>> 
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • That explains the ints. Thank you. It has been about 10 years since C++ 101 back in college and just trying to learn something new. – BrianStoiber Feb 16 '15 at 16:44
0

If you check 1/4 you'll get 0, not 0.25. Because 1 and 4 are ints.

In [42]: 1/4
Out[42]: 0

In [43]: 1.0/4
Out[43]: 0.25

so

(3 + 2 + 1 - 5) = 1
(4 % 2) = 0
(1 / 4) = 0

and the final result will be

1 + 0 + 0 + 6 = 7
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • Thank you Roman, that make a lot more sense than just pointing to the modulo explanation like the people that marked it as a duplicate. Didn't realize they were considered ints so that anything other than a whole number would be considered. So (4 % 2) is basically written out saying (4 goes into 2) = 0 times. So (3 % 11) would actually be 3? 3/11 = 0 3 - 0 = 3 Right? – BrianStoiber Feb 16 '15 at 16:30
  • No, not 4 goes into to. 2 goes into 4 with 0 remainder. The modulus of division is the integer remainder – joel goldstick Feb 16 '15 at 17:04
  • @BrianStoiber yes, you can also check function `divmod(x, y)` which will return you a tuple `(quotient, remainder)`. So `divmod(5,2) = (2, 1)`. – Roman Pekar Feb 16 '15 at 20:35