You can learn about Operators in Python Programs with Outputs helped you to understand the language better.

## Python Programming – Arithmetic Operators

Arithmetic operators perform basic arithmetic operations. Arithmetic operators, such as +, -, *, / , % (modulus), ** (exponent), etc., are used for mathematical calculations. An arithmetic expression is made up of constants, variables, a combination of both, or a function call, connected by arithmetic operators. Some of these operators also work on data types other than numbers, but they may work differently. For example, + adds two numbers (2 + 2 gives the result 4). But concatenating numbers gives a string (‘2’ + ‘2’ gives the result ’22’).
You cannot use an operator with two incompatible data types.

For example, if you try to use + with an integer and a string, Python returns an error. An arithmetic expression is made up of constants, variables, a combination of both, or a function call, connected by arithmetic operators. (See Figure 4.1). Normally, operators are said to be either unary or binary. A unary operator has only one operand while a binary operator has two operands. In its unary mode with a single operand, a minus sign is usually a sign-changing operator, while in its binary mode with two operands, a minus sign is usually a subtraction operator.

Working with Arithmetic Operators

The binary arithmetic operator requires two operands to operate upon them. Assuming variable a holds 10 and variable b holds 20 then:
(a) + (addition or plus) say a + b, will give 30.
(b) – (subtraction or minus) say a – b will give -10.
(c) * (multiplication) say a * b, will give 200.
(d) / (slash for division) say b / a will give 2.0.
(e) % (modulus operator for the remainder), say b % a will give 0.
(f) ** [exponent – Performs exponential (power) calculation on operators]
a = 2
b = 3
c = a**b will give 8.
(g) // (Floor division) – It refers to the division of operands where the result is the quotient in which the digits after the decimal point are removed. In other words, the operation that divides two numbers and chops off the fraction part is called floor division.
a=9
b=2
9 / / 2 will give 4
and
a=9.0
b=2.0
9.0/ /2.0 will give 4.0

Example 1.
Demo of arithmetic operators.

 # Demo of arithmetic operators a = 20 b = 10 c = 0 c = a + b print ( ” Sum of a + b is “, c ) c = a – b print ( ” Difference a – b is “, c ) c = a * b print ( ” Multiplication a * b is “, c ) c = a / b print(“Division a/b is “, c) c = a % b print ( ” Remainder a%b is “, c ) a = 2 b = 3 c = a**b print ( ” Exponent a**b is “, c ) a = 10 b = 5 c = a//b print ( ” Floor division a//b is “, c )RUN Sum of a + b is 30 Difference a – b is 10 Multiplication a * b is 200 Division a/b is 2.0 Remainder a%b is 0 Exponentiation a**b is 8 Floor division a//b is 2

Let’s Try

Exponentiation refers to finding powers. Python uses ** before a power. Exponents do not need to be integers. For example, 0.5 power will produce a square root. Try the following in the Shell:

 >>> 3 * * 4 >>> 9 * * . 5 >>> ( 1 + 1 ) * * ( 5 – 2 ) >>> 5 * 2 * * 3 >>> 2 * * . 5 >>> 3 * 1 * * 3

Write the output of following binary arithmetic operations:

 # Working with binary arithmetic operators a = 4 b = 2 sum = a+b sub = a-b mult = a*b divi = a/b modu = a%b expo = a**2 print ( ” Sum of a + b is “, sum ) print ( ” Subtraction of a – b is “, sub ) print( ” Multiplication of a * b is “, mult ) print ( ” Division of a / b is “, divi ) print ( ” Modulus of a % b is “, modu ) print ( ” Exponent of a ** b is “, expo )

Example 2.
Program to calculate area of a triangle using formula 1/2*base*height.

 # Program to calculate area of a triangle using formula l/2*base*height base = float ( input ( ” Enter base of a triangle : ” ) ) height = float ( input ( ” Enter height of a triangle : ” ) ) area_of_triangle = ( 1/2* base * height ) print ( ” Area of a triangle: “,area_of_triangle )RUN >>> Enter base of a triangle: 3.5 Enter the height of a triangle: 5.5 Area of a triangle: 9.625 >>>

Example 3.
Program to print quotient.

 # Program to print Quotient a = int ( input ( ” Enter first number: ” ) ) b = int ( input ( ” Enter second number: ” ) ) print ( ” Quotient : “, a/b )RUN >>> Enter first number: 5 Enter second number: 2 Quotient : 2.5 >>>

Example 4.
Program to calculate simple interest.

 # Program to calculate simple interest principal = int ( input ( “Enter any principal amount: ” ) ) rate = int ( input ( ” Enter rate of interest: ” ) ) time = int ( input  ( ” Enter time: ” ) ) si = ( principal*rate*time ) / 100 print ( ” Simple Interest = “, si )RUN >>> Enter any principal amount: 3000 Enter rate of interest: 10 Enter time: 12 Simple Interest = 3600.0 >>>

Example 5.
Program to calculate area of a triangle using Heron’s formula.

 # Program to calculate area of a triangle using Heron’s formula sidel = float ( input ( ” Enter first side of a triangle : ” ) ) side2 = float ( input ( ” Enter second side of a triangle : ” ) ) side3 = float ( input ( ” Enter third side of a triangle : ” ) )s=(side1+side2+side3)/2 area =(s*(s-side1)*(s-side2)*(s-side3))* * 0.5 print ( ” Area of a triangle is : ” , area )RUN >>> Enter the first side of a triangle: 6 Enter the second side of a triangle: 4 Enter the third side of a triangle: 4 The area of a triangle is: 7.937253933193772 >>>

Example 6.
Program to calculate area and perimeter of a parallelogram.

 # Program to calculate area and perimeter of parallelogram l = float(input(“Enter length: “)) w = float(input(“Enter width: “)) h = float(input(“Enter height: “))area_parallelogram = 1*h peri_parallelogram = 2*1 + 2*w print ( ” The area of the parallelogram is “, area_parallelogram ) print( ” The perimeter of the parallelogram is “, periparallelogram )RUN >>> Enter length: 5.2 Enter width: 2.0 Enter height: 1.5 The area of the parallelogram is 7.800000000000001 The perimeter of the parallelogram is 14.4 >>>

Example 7.
Program demonstrating working with power operator.

 # Program demonstrating working with power operator x = int ( input ( ” Please enter an integer: ” ) ) print ( ‘ value of x = ‘, x ) print ( ‘ x**2 = ‘, x**2 ) print ( ‘ x**3 = ‘, x**3 ) print ( ‘ x**4 = ‘, x**4 )RUN >>> Please enter an integer: 2 value of x = 2 x* *2 = 4 x**3 = 8 x**4 = 16 >>>

Example 8.
Demo of division operator (/).

 # Demo of division operator (/) dividend, divisor = eval ( input ( ‘ Please enter two numbers to divide: ‘) ) print ( dividend, ‘/’, divisor, “=”, dividend/divisor )RUN >>> Please enter two numbers to divide: 8 , 2 8 / 2 = 4 . 0 >>> Please enter two numbers to divide: 2 , 8 2 / 8 = 0 . 25 >>>

Example 9.
Demo of modulus operator (%).

 # Demo of modulus operator (%). num1 = int(input(“Enter first number : “)) num2 = int(input(“Enter second number : “)) remainder = num1%num2 print(“Remainder: “, remainder)RUN >>> Enter first number: 7 Enter second number: 2 Remainder: 1 >>> Enter first number: 10 Enter second number : 2 Remainder: 0 >>>

Hierarchy of Arithmetic Operators

Calculations in Python are done in a specific order, which is called operator precedence. In arithmetic, operations in parentheses are performed first. Operators in higher rows are evaluated before operators in lower rows. If multiple operators appear in a single cell in the table which is equal in precedence they are evaluated from left to right.

When two or more operators appear in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows the mathematical convention. The acronym PEMDAS (Parentheses Exponentiation Multiplication Division Addition and Subtraction) is a useful way to remember the rules. The hierarchy or order of operation of arithmetic operators is as follows:
(a) Parentheses have the highest precedence. Since expressions in parentheses are evaluated first, 2 * (4-1) is 6, and (l+l)**(4-2) is 4.

(b) Exponentiation has the next highest precedence and is evaluated from right to left, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.

(c) Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So, when you have multiple expressions like 2*3-1 multiplication and division are performed before addition and subtraction. Hence, the result is 5, not 4. The result of 6+4/2 is 8.0, not 5.0.

(d) Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and then the result is multiplied by pi. To divide by 2n, you can use parentheses or write degrees / 2 / pi.
The precedence of operators decides the order in which different operators are applied. Associativity of operators decides the order in which multiple occurrences of the same level operator are applied.

Example 10.
1 + ((3 + 1) / (8 -4) ~ 5)
Evaluation of the expression is shown in Figure 4.10 Division and Remainder
The division operator (/) is used for division. It divides the left-hand operand by the right-hand operand. For example:

5/2                 evaluates to            2.5
7/2                 evaluates to            3.5
1/3                 evaluates to            0.3333333333333333
5.0/2              evaluates to            2.5
99/100           evaluates to            0.99
99/100. . 0     evaluates to            0.99
99.0/100        evaluates to            0.99
-5/2               evaluates to            -2.5
7/-2               evaluates to            -3.5
1/3                evaluates to             0.3333333333333333

Python also provides int( ) functions that can be used to convert numbers into ints. Conversion to an int simply discards the fractional part of a float; the value is truncated, not rounded. For example,

>>> int ( 4 . 5 )
4
>>> int ( 3 . 9 )
3
>>> float ( int ( 3 . 3) )
3.0
>>> int ( float ( 3 . 3 ) )
3
>>> int ( float ( 3 ) )
3

• In Python 2, the result of the division of two integers is rounded to the nearest integer. As a result, 3/2 will show 1. In order to obtain a floating-point division, a numerator or denominator must be explicitly used as afloat. Hence, the use of either 3.0/2 or 3/2.0 or 3.0/2.0 will result in 1.5.
Python 3 evaluates 3/2 as 1.5 by default.

Example 11.

Given the following declarations:
m = 3
n = 4
x = 2.5
y = 1.0
Evaluate the values for the following expressions:
(a) m + n + x + y
(b) m + x * n + y
(c) x / y + m / n
(d) x-y*m + y/ n
(e) x / 0
Solution:
(a) The expression (m + n + x + y) is equal to 3 + 4 + 2.5 + 1.0 = 10.5.

(b) The expression (m + x * n + y) is equivalent to ((m + (x * n) + y)) because the precedence of * is higher than that of +. Substituting the values of the variables, you get:
((3 + (2.5 * 4) + 1.0)) = 14.0

(c) The expression (x / y + m / n) is equivalent to ((x / y) + (m / n)). Thus, substituting the values of x, y, m and n, you get:
(2.5 / 1.0) + (3 / 4) = 3.25

(d) The expression (x – y * m + y / n) is equivalent to (x – (y * m)) + (y / n). Thus, substituting the values of x, y, m and n, you get:
(2.5 – (1.0 * 3) + (1.0 / 4)), i.e., 2.5 – 3.0 + .25, i.e., -0.25.
(e) x / 0 is undefined. Any number divided by zero is infinite and hence the value is not defined, so, you will get an error message.

• Note: Python 2 displays long integers with an uppercase L, but in Python 3 it is not used.

Let’s Try

Given the following declarations:
m = 5
n = 4
x = 2.5
y = 2.0
Evaluate the values for the following expressions:
(a) m + n + x + y
(b) m + x * n + y
(c) x / y + m / n
(d) x-y*m + y / n
(e) x / 0

Remainder Operator (%)
Unlike the other arithmetic operators which accept both integer and floating-point operands, the remainder operator (also called the modulus operator) accepts only the integer value of operands. The result¬ing value is the remainder of the first operand divided by the second operand. In Python, the modulus operator is a percent sign(%). For example, the expression:
9 % 5
has a value of 4 because 5 goes into 9 once, with a remainder of 4. The expression:
10 % 5
has a value of zero because 5 goes into 10 two times, with no remainder.

Let’s Try

Assign the given values to variable and write the output of the following operations:

 X = 27 .0 ;  Y = 12 ,  Z = 2 >>> X/Y >>> X//Y >>> X**Z >>> Y**Z >>> Y%Z >>> (Y*Z)%2 >>> Y+Z%2 >>> Y/Z *2