Arithmetic Operations
An operator is a symbol that tells the compiler that either a mathematical or a logical manipulation has to be done. In this lab you will be studying about the Arithmetic Operations.
They are of the following types :
Addition Operator ( + )
The addition operator is used to add two numbers. It is placed between two numbers that are to be added.
Syntax : number1 + number2
Program:
Output:
x + y = 5
Subtraction Operator ( - )
The subtraction operator is used to subtract two numbers. It is placed between two numbers that are to be subtracted. The right placed number is subtracted from the one that is placed at left.
Syntax : number1 - number2
Program:
Output:
x – y = 1
Multiplication Operator ( * )
The multiplication operator is used to multiply two numbers. It is also placed between the two numbers that are to be operated.
Syntax : number1 * number2
Program:
Output:
x * y = 300
Division Operator ( / )
The division operator is used to divide two numbers. It is used between the numbers that are to be operated.
Syntax : number1 / number2
It has some different rules that have to be kept in mind before operating the numbers. Python2 operates the division operator by taking the integral value.
Example : 6 / 4
Answer : This operation will be solved in Python2 by taking the integral value i.e 1. Therefore, the answer of 6 / 4 = 1
This problem can be taken care by Type Casting. Type Casting is used to convert the output in a desired form.
To get the correct answer of the above example, we will type cast it using float data type.
Program:
Output:
x/y = 3.0
Example : float(6 / 4)
Answer : Now, the output will be changed into float type and the answer will be 1.5.
float(6 / 4) = 1.5
There's another way of solving such problem. By using one float type input, we can get the desired answer.
Example : 6.0 / 4
Answer : 1.5
Modulus Operation ( % )
It is used to give out the remainder of a division operation. It is also placed between numbers. The right placed number divides the one on the left and the remainder is given as output.
Syntax : number1 % number2
Program:
Output:
x % y = 2
Exponent Operation ( ** )
It is used to perform exponential calculations. The right placed number acts as the power.
Syntax : number1* *number2
Program:
Output:
X * * y = 8
Floor Division Operator ( // )
It is used to perform floor division. This gives the result in int format.
Syntax : number1 // number2
Program:
Output:
X // y = 0
45 / 9 will give 5.0 where as 45 // 9 will give 5