Before we can get into some "real" programming we have to learn about some of the basic pieces that make up a program. You will begin with short program, and we will add pieces to that.
Chapter 0: The Study of Computer Science
Chapter 1: Beginnings
For those who have not yet purchased a text here is a draft of Chapters 0 and 1.
In [1]: round(4.5) Out[1]: 4 # returned an int, rounded down In [2]: round(4.51) Out[2]: 5 # returned an int, rounded up In [3]: round(4.51,1) Out[3]: 4.5 # returned a float, rounded to one decimal place
In [1]: round(26.5) Out[1]: 26 # (6 is even so round down) In [2]: round(25.5) Out[2]: 26 # (5 is odd so round up)
In [1]: round(3.5) Out[1]: 4 # returned an int, rounded up In [2]: round(4.5) Out[2]: 4 # returned an int, rounded down In [3]: round(1.5) Out[3]: 2 # returned an int, rounded up In [4]: round(2.5) Out[4]: 2 # returned an int, rounded down
round()
for floats can be surprising. For example, round(2.675,2)
gives 2.67 instead of the expected 2.68.
It's a result of the fact that most decimal fractions can't be represented exactly as a float. When the decimal 2.675 is converted to a binary floating-point number,
it's again replaced with a binary approximation, whose exact value is: 2.67499999999999982236431605997495353221893310546875
Due to this, it is rounded down to 2.67
.