Hey, Folks: Using the problem from 6.00 Practice Quiz 1 #2, I get False, True when running it. I was hoping someone could help me: Why is the first check statement of x False? It seems like it should be True and x is indeed 11.0 when I insert print statements before and after. x = 10.0 for i in range(10): x += 0.1 print x == 11.0, 'why is this printing false?' for i in range(10): x -= 0.1 print x == 10.0
lets break down these statements "for i in range (10)" This means for i in range 0,1,2,3,4,5,6,7,8,9,10 Note that there are eleven numbers here, not ten, since we count from zero by default. If you want to count from 1, you would use "range(1,10)". "x += x + 0.1" This means assign the variable x with x + 0.1 Do this eleven times , starting with x = 10 the computer will do 10.1, 10.2, 10.3 , ... 11.1 now if you subtract 0.1 eleven times, you will be back to 10 "for i in range (10) x -= 0.1 " accomplishes just this. May i ask what programming language you are learning
Hi, perl: first, thanks so much for this! Seeing it written was helpful. I think my lack of understanding had to do with floats and how they’re displayed. In Python (what I’m using for this class) print range(10) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], so I think I am working with 10 iterations. Also, by inserting “print repr(x)” statements before and after the “print x == 11.0” I finally figured out that x was actually 10.999999 after the final iteration… but was being displayed as 11.0. By doing the same operations in reverse, though, even large float values end up exactly where we started. (which is why it prints True after the second loop). Thank you!
Join our real-time social learning platform and learn together with your friends!