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.

- Your First Program
- Program Elements
- Working some simple examples
- Round() behavior
- Here are three examples that illustrate how calling the round() function with no second argument, it returns an int. The second argument indicates how many significant digits to the right of a decimal point so a non-zero second argument will return a float. Also, note how it rounds with 0.5.
- Python uses "round to nearest, ties to nearest even": When the value you intend to round off is a five, you MUST look at the previous value. If it is even, you round down. If it is odd, you round up. It is called round half to even. For example,
- Couple more examples:
- The behavior of
`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`

.

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