Course 1.3Lesson 4 of 5
Python has ready-made number tools. round(x, n) rounds to n decimal places, and round(x) rounds to a whole number. int() cuts off the decimal part. abs() gives the size of a number without its sign. min() and max() give the smallest and the biggest of several numbers. divmod(a, b) gives the quotient and the remainder together. Use round() before you show the result of a division.
Try the code and the simulations beside the lesson.
After this lesson you can
round() and int(),abs(), andmin(), max() and divmod() to write short programs.You met print() already. It is a function: a ready-made helper with a name and brackets. Python has many functions for numbers. They are always ready, and you do not have to install anything. Here are the five that you will use most.
A note on round(2.5): it gives 2, and not 3. Python rounds a number that is exactly in the middle to the nearest even whole number. This is also done in science, because over many numbers it makes less error. You do not need to worry about it, but now you will not be surprised.
Try 2.5 and 3.5 as well. At exactly a half, Python rounds to the even neighbour.
A teacher has the marks of five students: 72, 85, 91, 64, 78. A short program can find the highest, the lowest, and the gap.
highest = max(72, 85, 91, 64, 78) is 91.lowest = min(72, 85, 91, 64, 78) is 64.gap = highest - lowest is 27.(72 + 85 + 91 + 64 + 78) / 5, which is 78.0.When you show a result, think about how many digits the reader needs. A mark of 78.0 is easier to read than 78.00000000001.
int() when you want to round. int(2.9) is 2. Use round(2.9), which is 3.round() gives an int with one number and a float with two. round(2.6) is 3, and round(2.6, 1) is 2.6.abs of a sum. abs(-3 + 5) is 2, but abs(-3) + abs(5) is 8. The brackets decide.min(3, 4, 5 without the closing bracket.max(3 4 5).Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
round() and abs() on a few numbers. The checker confirms your answers.divmod() to take 472 apart into hundreds, tens and ones.round(x, n) rounds to n places. int(x) cuts off the decimal part.abs(x) is the size of x. min() and max() pick the smallest and the biggest.divmod(a, b) gives the quotient and the remainder together.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
round(7.46, 1) and int(7.46)?abs(3 - 10)?quotient and remainder of 100 / 7 with one line?max(5, -9, 2)?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.