Python can add, subtract, multiply and divide, and it has special signs for whole-number division, the remainder and powers. In this course you use them to solve everyday problems, learn which sign Python does first, meet the number tools round, abs and divmod, and finish with two small projects: a machine that gives change, and a program that turns seconds into a clock time. Every lesson has practice that checks your answers.
5 lessons, about 2 h 35 min5 simulations13 problems10 practice questionsPython in every lesson
Python does arithmetic with five signs: the plus, the minus, the star for multiply, the slash for divide and the double star for a power. Division with / always gives a float, even when the answer is a whole number. A number with a decimal point makes the answer a float. Brackets group a part of a sum. Python works out every sum before print() shows the answer, so it can be used like a calculator, with variables to keep the numbers.
The // sign gives how many whole times the second number fits into the first. The % sign gives the remainder that is left. Together they split a number into whole groups and what is left over, so the answer of a division can be written as quotient times divisor plus remainder. The ** sign is the power, and a power of 0.5 is a square root. The remainder is used to test for even and odd numbers, to find the last digit of a number, and for the arithmetic of a clock.
Python follows the order of mathematics: brackets first, then powers, then multiplication and division from left to right, then addition and subtraction from left to right. So 2 + 3 * 4 is 14, and (2 + 3) * 4 is 20. When you are not sure, use brackets, because they cost nothing and make the order clear. The power is done before a minus sign, so -2 ** 2 is -4. A formula such as an average needs brackets around the sum.
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.
In this project we write two small programs that use the whole course. A change maker works out how many notes of 100, 50, 20, 10 and 5 and how many coins of 1 rupee are needed for an amount, by using // for how many and % for what is left, from the biggest note to the smallest. A clock program turns a number of seconds into hours, minutes and seconds. Both programs are checked by hand, by testing with other numbers, and by looking at the edge cases.
Log in to join the discussion.
Loading…