440,034 Members | 2,000 Online
Need help? Post your question and get tips & solutions from a community of 440,034 IT Pros & Developers. It's quick & easy.

# Easiest question you'll get all day, Python math related

 P: 4 Hi guys -- Just started learning Python last night. Working with 2.7. In the guide I'm using, this was one of the lines we worked with: print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 This prints: 7 I don't understand this. I BELIEVE that modulos and division are processed first here, so wouldn't it look like: 3 + 2 + 1 - 5 + 0 - 1 + 6 thus printing: 6 I was under the impression that this would NOT create a fraction, thus 1 / 4 returns 1. I'm getting the impression this is incorrect. Any advice and tips to move me along here would be great. Thank you! Oct 25 '11 #1

`1/4` returns 0 in Python 2.xx.

5 Replies

 Expert Mod 2.5K+ P: 2,851 `1/4` returns 0 in Python 2.xx. Oct 25 '11 #2

 Expert Mod 5K+ P: 9,731 That's weird bvdet... The first time I stepped through this code in my head I came up with 6: Expand|Select|Wrap|Line Numbers 3 + 2 = 5 5 + 1 = 6 6 - 5 = 1 1 + 4 = 5 5 % 2 = 1 1 - 1 = 0 0/4 = 0 0 + 6 = 6 The only way that I could see it coming to 7 is if the division was done for 1/4 before the subtraction: Expand|Select|Wrap|Line Numbers 3 + 2 = 5 5 + 1 = 6 6 - 5 = 1 1 + 4 = 5 5 % 2 = 1 1 - 1/4 = 1 1 + 6 = 7 Unless maybe it goes backwards like some math things I've worked with in my comp sci classes...where the operands and operators are pushed on to a stack or into a tree and then calculations are done it... Oct 25 '11 #3

 P: 4 Thank you very much, guys. The way I see it, Frinavale, after reading bvdet's comment, is like this: 3 + 2 + 1 - 5 + (4 % 2 = 0) - (1 / 4 = 0) + 6 thus, 3 + 2 + 1 - 5 + 0 - 0 + 6 = 7 Always interested to hear more insight on it. Thanks again, guys! Oct 25 '11 #4

 Expert Mod 2.5K+ P: 2,851 Order of operator precedence is 1. * / % 2. + - so Expand|Select|Wrap|Line Numbers >>> (3 + 2 + 1 - 5) + (4 % 2) - (1 / 4) + 6 7 >>>  `1+0+0+6 = 7` Oct 25 '11 #5

 Expert Mod 5K+ P: 9,731 Cool :) Oct 25 '11 #6