Course 1.3Lesson 3 of 5
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.
Try the code and the simulations beside the lesson.
After this lesson you can
What is 2 + 3 * 4? A person who reads from left to right says: 2 plus 3 is 5, times 4 is 20. A person who knows the rules of mathematics says: multiplication comes first, 3 times 4 is 12, and 2 plus 12 is 14. Python follows the rules of mathematics.
The order, from first to last:
( ).**.* / // %, from left to right.+ -, from left to right.The average of two marks is the sum divided by 2. Look at a mistake that many beginners make.
Why did wrong go wrong? In mark_1 + mark_2 / 2, the division comes first: 90 / 2 is 45, and then 80 + 45 is 125. In (mark_1 + mark_2) / 2, the brackets make the sum first. We meant to add first, but Python does what you wrote.
In mark_1 + mark_2 / 2, only mark_2 is halved, because division comes before addition.
Extra brackets never do harm. (2 * 3) + 4 is the same as 2 * 3 + 4, but it shows the reader what you mean. If you cannot remember the order, put in brackets. Experienced programmers do this all the time.
Take a formula from science: the distance of a body that starts from rest is s = (1/2) * a * t². In Python:
s = 0.5 * a * t ** 2 is right. The power t ** 2 is done first, and then the multiplications.s = 1 / 2 * a * t ** 2 is also right. 1 / 2 is 0.5, and the rest goes left to right.s = (a * t) ** 2 / 2 is wrong. The bracket makes (a * t) squared, which is not the formula.Always check a formula with a simple example: take a = 2 and t = 3. The right answer is 0.5 * 2 * 9 = 9.
a + b / 2 is not (a + b) / 2.(a + b) / (c + d), you need both pairs of brackets.-3 ** 2 is -9.8 / 4 / 2 is 1.0, and not 4.0.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:
* / // % from left to right, then + - from left to right.2 + 3 * 4 is 14, and (2 + 3) * 4 is 20.-2 ** 2 is -4, because the power comes before the minus.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
4 + 6 / 2 and (4 + 6) / 2?2 ** 2 ** 3? (The power sign goes from right to left.)a, b and c in Python.10 - 2 * 3 + 1?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.