Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do order of operations go on Python?

My question looks like this:

  10-7//2*3+1 

I am supposed to solve the equation.

My answer seems to come out as 8 when using PEMDAS:

First its's 2*3 = 6; 10-7//6+1
second = 7//6= 1; 10-1+1
Third = 10-8 = 8;

But when putting it into python, I get a 2. Why is this so?

It seems the programs order is as such:

first: 7//2=3; 10-3*3+1
second: 3*3=9; 10-9+1
third:10-9+1= 2; 2

I don't get it.

like image 935
Ashton Avatar asked Feb 22 '18 21:02

Ashton


People also ask

How does Python do order of operations?

Python will always evaluate the arithmetic operators first (** is highest, then multiplication/division, then addition/subtraction). Next comes the relational operators. Finally, the logical operators are done last.

What is the correct order of precedence for operations in Python?

The correct answer to the question “What is the order of precedence in Python” is option (a). i,ii,iii,iv,v,vi. Python also follows the same concept of precedence as used in Math. In Math, it is known as BODMAS, and in Python, you could remember PEMDAS as the order of precedence.

Does Python follow Pemdas or Bodmas?

Operator Precedence Python follows the traditional mathematical rules of precedence, which state that multiplication and division are done before addition and subtraction. (You may remember BODMAS.) This means in our example above, 2 and 4 are multiplied first, and then the result is subtracted from 10.

How does the order of operation go?

The order of operations is a rule that tells the correct sequence of steps for evaluating a math expression. We can remember the order using PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right).


1 Answers

PEMDAS is better expressed as

P   Parentheses, then
E   Exponents, then
MD  Multiplication and division, left to right, then
AS  Addition and subtraction, left to right

So in your expression, the division should be done before the multiplication, since it is to the left of the multiplication. After those are done, then do the subtraction then the addition.

like image 100
Rory Daulton Avatar answered Sep 20 '22 16:09

Rory Daulton