Expressions, Precedence & Associativity in Python

In this post, let's talk about especially floor division & other expressions such as exponent/power of operators from expressions and the precedence & associativity in Python. 

As I'm much familiar with C,  let's compare the division with C. 

1
2
3
4
5
6
7
8
#include <stdio.h>

void main()
{
    printf(" Result in format specifier %%d %d \n", 50/9);
    printf(" Result in format specifier %%f %f \n", 50/9);
    return; 
}


Output:

1
2
 Result in format specifier %d 5 
 Result in format specifier %f -408385434184548374919446724357


In C, Java, C++, the result will be 5 only for the division of 50/9. In the case of Python, you will get the result as a float value by default. 

>>> 50/9
5.555555555555555
>>> 


Basically, the python always gives result in the decimal point. A single number of quotient can be achieved by using // (two forward slashes) which is called floor division in Python. 

>>> 50/9            >>>>>> Normal division 
5.555555555555555
>>>



The term operators and operands are the same in Python too. The operands are ideally the literals or constants in the above image. There are few Python-specific operators such as **.  



This table lists all the operator's precedence from the highest to lowest & its associativity. The mnemonic PEMDAS, which is used to remember this easily, is Please Excuse, My Dear Aunt Sally.  






Python IDLE is a much easier version, but there are more IDEs are available for the development of python. As of now, I've installed IDLE.

Reference: GeeksforGeeks

Comments

  1. i am a banananananananannanananananananaaaaa

    ReplyDelete

Post a Comment