0

I don't get why this function returns 2.0.

1+1/2*2

For order of operations, I thought it would be multiplication first, then division, left to right, so 1+1/4 to 1+.25 or maybe even return 2/4 =0.5...

I am really confused how it outputs 2.0.

Thanks in advance! Currently studying for an exam.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • I'm seeing it reads it as like, 1+1/2 * 2, so 2/2 * 2, or 1*2 which equals 2; so do we not do multiplication first then? I was trying to go off of PEMDAS but I think I probably just over complicated it and should do division first as I encounter it while reading left to right? – statisticalerror Jun 10 '21 at 05:53
  • " I thought it would be multiplication first, then division, left to right," multiplication and division have the same precedence, just like in arithmetic – juanpa.arrivillaga Jun 10 '21 at 17:07
  • Don't add *another, unrelated question*. Please take a look at the [help] and [ask]. This isn't your personal tutorial service. – juanpa.arrivillaga Jun 10 '21 at 17:08
  • @statisticalerror try searching for similar question on stackoverflow, which may have answered already. https://stackoverflow.com/a/48937537/14429185 – nobleknight Jun 11 '21 at 04:51

2 Answers2

1

As for the multiplication and division, the order is left to right. So here is the division first. 1 + 1 / 2 * 2 = 1 + 0.5 * 2 = 1 + 1 = 2

For the next problem, I think if a == 'A' or 'B' is 2 expressions, a == 'A' and 'B'. I've learned a little about C++, and the 'B' refers 66 in the ASCII, which is not 0, so the expression 'B' is always true. Maybe in python it will be the same. So the code should be if a == 'A' or a == 'B':

Fallot
  • 11
  • 2
0

See the stackoverflow post: How do order of operations go on Python?

According to that your math, 1+1/2*2, is as follows:

           /  1  \
ans = 1 + (  ---  )  X 2
           \  2  /

    = 1 + (0.5 X 2)

    = 1 + 1

    = 2

Multiplication and division are in the same group and are performed left to right (aggregating the answers from the link I referenced).

Enjoy the ASCII art ¯\_(ツ)_/¯

Mark Davich
  • 512
  • 1
  • 5
  • 16