Python Arithmetic Operators
Operators are used to do action or process on variables and operands. The operator usually represents as symbol for doing an action. Python has different type of operators like Arithmetic, Assignment, Relational / Comparison , Logical, Bitwise, Identity and Membership operators. Every operators are using to do different kind of operations.
In this tutorial we will learn about Python Arithmetic Operators.
Python Arithmetic Operators
Python Arithmetic operators are used to perform the mathematical operations.
Operator | Description | Syntax | Example |
---|---|---|---|
+ | Adds the values of two operands | var1 + var2 | a + b |
- | subtracts the values of two operands | var1-var2 | a - b |
* | Multiplies the values of two operands | var1 * var2 | a * b |
/ | Divides the values of two operands | var1/var2 | a / b |
% | Modulus - Returns the remainder of first operand divided by second operand | var1%var2 | a % b |
** | Exponentiation - Returns the first operand power of second operand | var1 ** var2 | a ** b |
// | Floor Division - Divides the values of two operands and returns the integer value | var1//var2 | a//b |
Code Example:-
>>> var1 = 2
>>> var2 = 3
>>> print('Addition => ' + str(var1) + ' + ' + str(var2) + ' = ' + str(var1+var2))
Addition => 2 + 3 = 5
>>> var1 = 5
>>> var2 = 3
>>> print('Subtraction => ' + str(var1) + ' - ' + str(var2) + ' = ' + str(var1-var2))
Subtraction => 5 - 3 = 2
>>> var1 = 5
>>> var2 = 6
>>> print('Multiplication => ' + str(var1) + ' * ' + str(var2) + ' = ' + str(var1*var2))
Multiplication => 5 * 6 = 30
>>> var1 = 30
>>> var2 = 6
>>> print('Division => ' + str(var1) + ' / ' + str(var2) + ' = ' + str(var1/var2))
Division => 30 / 6 = 5.0
>>> var1 = 3
>>> var2 = 2
>>> print('Modulus / Reminders => ' + str(var1) + ' % ' + str(var2) + ' = ' + str(var1%var2))
Modulus / Reminders => 3 % 2 = 1
>>> var1 = 2
>>> var2 = 2
>>> print('Exponentiation => ' + str(var1) + ' ** ' + str(var2) + ' = ' + str(var1**var2))
Exponentiation => 2 ** 2 = 4
>>> var1 = 5
>>> var2 = 3
>>> print('Floor Division => ' + str(var1) + ' // ' + str(var2) + ' = ' + str(var1//var2))
Floor Division => 5 // 3 = 1
str() Function
Here we use str() function. The purpose of the function is convert the given object to string object.
Syntax for str()
str(object, encoding='utf-8', errors='strict')