Arithmetic Operators in Python execute mathematical computations between two numeric values or operands. Whether you are summing figures, using formulas, or dealing with scientific calculations, understanding how arithmetic computations function in Python and which operators are utilized to perform them is essential. This article will elucidate Python arithmetic operators, their syntax, and the detailed workings of operator precedence.
Arithmetic Operators are symbols in Python that enable users to execute fundamental mathematical calculations between two numerical values. Python provides operators for addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//). The availability of these defined operators eliminates the necessity for creating a function to perform these calculations.
Operands and Operators in Python
Operators are symbols that direct the interpreter to execute calculations (operations) on the operands. Operands are the values or variables upon which the interpreter performs the operations.
For example, in the expression “3 + 5,”(+) represents an operator, while 3 and 5 are the operands.
Types of Arithmetic Operators in Python
This section will explore the various types of operators in Python that were previously mentioned with illustrative code examples.
1. Addition (+)
This operator takes two operands and computes their total.
Example:
Python
Code Copied!
var isMobile = window.innerWidth “);
editor91364.setValue(decodedContent); // Set the default text
editor91364.clearSelection();
editor91364.setOptions({
maxLines: Infinity
});
function decodeHTML91364(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard91364() {
const code = editor91364.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor91364 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor91364 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode91364() {
var code = editor91364.getSession().getValue();
function closeoutput91364() {
var code = editor91364.getSession().getValue();
jQuery(“.maineditor91364″);
“““html
.code-editor-output”).hide();
}
// Bind event listeners to the buttons
document.getElementById(“copyBtn91364”).addEventListener(“click”, copyCodeToClipboard91364);
document.getElementById(“runBtn91364”).addEventListener(“click”, runCode91364);
document.getElementById(“closeoutputBtn91364”).addEventListener(“click”, closeoutput91364);
Result:
Clarification: In this scenario, we have combined 4 and 5.
2. Deduction (-)
This operator involves two operands and computes their difference.
Illustration:
Python
Code Duplicated!
var isMobile = window.innerWidth “);
editor89414.setValue(decodedContent); // Establish the default text
editor89414.clearSelection();
editor89414.setOptions({
maxLines: Infinity
});
function decodeHTML89414(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to replicate code to clipboard
function copyCodeToClipboard89414() {
const code = editor89414.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code replicated to clipboard!”);
data: {
language: “python”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output89414”).html(“
"+data+"");
jQuery(".maineditor89414 .code-editor-output").show();
jQuery("#runBtn89414 i.run-code").hide();
}
})
}
function closeoutput89414() {
var code = editor89414.getSession().getValue();
jQuery(".maineditor89414 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn89414").addEventListener("click", copyCodeToClipboard89414);
document.getElementById("runBtn89414").addEventListener("click", runCode89414);
document.getElementById("closeoutputBtn89414").addEventListener("click", closeoutput89414);
Result:
Clarification: In this case, we have deducted 5 from 4, yielding -1.
3. Multiplication (*)
This operator comprises two operands and provides their multiplication outcome.
Illustration:
Python
Code Duplicated!
Result:
Clarification: In this instance, we multiplied 4 by 5, yielding 20.
4. Division (/)
This operator separates the first operand by the second operand. It’s important to note that the division operator consistently returns a float value, even if the first operand divides evenly into the second or both operands are integers.
Instance:
Python
Code Copied!
Result:
Clarification: Here, we divided 4 by 5, which gave us 0.8.
5. Modulus (%)
This operator yields the remainder after performing division of the first operand by the second operand.
Instance:
Python
Code Copied!
``````html
"");
editor97463.setValue(decodedContent); // Assign the default text
editor97463.clearSelection();
editor97463.setOptions({
maxLines: Infinity
});
function decodeHTML97463(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard97463() {
const code = editor97463.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor97463 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor97463 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode97463() {
var code = editor97463.getSession().getValue();
jQuery("#runBtn97463 i.run-code").show();
jQuery(".output-tab").click();
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "python",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output97463").html("
"+data+"");
jQuery(".maineditor97463 .code-editor-output").show();
jQuery("#runBtn97463 i.run-code").hide();
}
});
}
function closeoutput97463() {
var code = editor97463.getSession().getValue();
jQuery(".maineditor97463 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn97463").addEventListener("click", copyCodeToClipboard97463);
document.getElementById("runBtn97463").addEventListener("click", runCode97463);
document.getElementById("closeoutputBtn97463").addEventListener("click", closeoutput97463);
Output:
Explanation: In this instance, we performed a modulus operation on 6 and 5, resulting in 1.
6. Exponentiation (**)
This operator raises the first operand to the power of the second operand, returning the outcome.
Example:
Python
Code Copied!
Output:
Explanation: In this scenario, we elevated 4 to the power of 5, resulting in 1024.
7. Floor Division (//)
This operator divides the first operand by the second and returns the highest integer that is less than or equal to the result.
function closeoutput4553() {
jQuery(".maineditor4553 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn4553").addEventListener("click", copyCodeToClipboard4553);
document.getElementById("runBtn4553").addEventListener("click", runCode4553);
document.getElementById("closeoutputBtn4553").addEventListener("click", closeoutput4553);
Outcome:
Analysis: Here, 4 divided by 5 equals 0.8. Floor division yields 0, which is the nearest whole number smaller than the calculated result.
Summary Table of Arithmetic Operators in Python
Operator
Symbol
Description
Example
Outcome
Addition
+
Combines two numbers
5 + 3
8
Subtraction
–
Removes the second number from the first
10 – 4
6
Multiplication
*
Multiplies two values
6 * 2
12
Division
/
Divides the first number by the second, returns float
7 / 2
3.5
Modulus
%
Produces the remainder
10 % 3
1
Exponentiation
**
Raises the first number to the power of the second
2 ** 3
8
Floor Division
//
Gives the integer portion of division
9 // 2
4
Operator Precedence and Associativity in Python
Operator precedence dictates the sequence in which operations are performed based on the hierarchy or priority of the utilized operators in a single expression. Python adheres to the same mathematical regulations of precedence, commonly known as BODMAS, to determine the order of evaluation.
B – Represents Brackets
O – Stands for orders (powers and roots)
D – Denotes Division
M – Indicates Multiplication
A – Represents Addition
S – Denotes Subtraction
Illustration:
Python
Code Duplicated!
editor32412.setValue(decodedContent); // Initialize the default text
editor32412.clearSelection();
editor32412.setOptions({
maxLines: Infinity
});
function decodeHTML32412(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard32412() {
const code = editor32412.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");
data: {
language: "python",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output32412").html("
"+data+"");
jQuery(".maineditor32412 .code-editor-output").show();
jQuery("#runBtn32412 i.run-code").hide();
}
})
}
function closeoutput32412() {
var code = editor32412.getSession().getValue();
jQuery(".maineditor32412 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn32412").addEventListener("click", copyCodeToClipboard32412);
document.getElementById("runBtn32412").addEventListener("click", runCode32412);
document.getElementById("closeoutputBtn32412").addEventListener("click", closeoutput32412);
Output:
Explanation: In this scenario, we provided a single expression containing various operators, and Python evaluated the expression according to the BODMAS principle.
Associativity dictates the direction in which operators are evaluated in cases where they share the same precedence. Left-associative implies evaluation from left to right, while Right-associative indicates evaluation from right to left.
Example:
Python
Code Duplicated!
Output:
Explanation: In both instances, the operators
``````html
hold the same priority level. Hence, we evaluated the expressions using the associativity principle. The computations proceed as 2 ** (3 ** 2)
Arithmetic Operations with Various Data Types
Python executes arithmetic operations across multiple numeric data types, such as integers and floats. Additionally, Python can manage complex numbers without requiring any external library. Let’s investigate them individually.
1. Integers (int)
The integer (int) data type in Python symbolizes whole numbers, both positive and negative, akin to mathematics. They can store positive values, negative values, and zero. This data type is frequently utilized in tasks such as counting, looping, indexing, and more. Integer operations are clear-cut and adhere to mathematical rules.
function closeoutput75814() {
var code = editor75814.getSession().getValue();
jQuery(".maineditor75814 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn75814").addEventListener("click", copyCodeToClipboard75814);
document.getElementById("runBtn75814").addEventListener("click", runCode75814);
document.getElementById("closeoutputBtn75814").addEventListener("click", closeoutput75814);
Output:
Explanation: In this instance, we performed several arithmetic operations on integers, yielding integer results.
2. Float (float)
Floating-point numbers in Python signify real numbers in mathematical contexts. These data types are utilized when heightened accuracy is essential in scenarios like scientific computations, financial records, and beyond. All arithmetic operators function with floats and generally return as floats to maintain accuracy.
data: {
language: "python",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output72487").html("
"+data+"");
jQuery(".maineditor72487 .code-editor-output").show();
jQuery("#runBtn72487 i.run-code").hide();
}
})
}
function concealOutput72487() {
var code = editor72487.getSession().getValue();
jQuery(".maineditor72487 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn72487").addEventListener("click", copyCodeToClipboard72487);
document.getElementById("runBtn72487").addEventListener("click", executeCode72487);
document.getElementById("closeoutputBtn72487").addEventListener("click", concealOutput72487);
Result:
Clarification: In this section, we divided, multiplied, and subtracted float operands. All outcomes were floats.
3. Complex Numbers
Python is distinctive because it includes inherent support for complex numbers. This indicates you don't need to import any library to declare a complex number. Simply use j for the imaginary component. In Python, the letter j represents the imaginary aspect. Complex numbers consistently yield complex results when arithmetic operations are executed on them.
Illustration:
Python
Code Copied!
Result:
Clarification: In this section, we carried out several arithmetic operations on complex numbers.
Arithmetic Operations with Type Conversion in Python
Python is capable of conducting arithmetic operations between distinct data types, such as between int and float, int and complex numbers, or float and complex numbers. Python employs implicit and explicit type conversion to adapt the operands to a compatible type. This guarantees that the operation does not lead to unexpected behaviors and results.
In Implicit Type Conversion, Python automatically transforms one data type into another during arithmetic operations.
``````html
when required. This is termed Type Coercion.
In Explicit Type Conversion, the developer voluntarily transforms one data type into another employing built-in functions such as int(), float(), and complex(). This is referred to as Type Casting.
1. Int and Float
When an int and a float serve as operands, Python automatically converts the int value into a float value prior to computing the operation's outcome. The resulting type is consistently a float.
function closeoutput26608() {
var code = editor26608.getSession().getValue();
jQuery(".maineditor26608 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn26608").addEventListener("click", copyCodeToClipboard26608);
document.getElementById("runBtn26608").addEventListener("click", runCode26608);
document.getElementById("closeoutputBtn26608").addEventListener("click", closeoutput26608);
Output:
Explanation: In this instance, we executed arithmetic calculations using integers and floats. The outcome was of float data type.
2. Float and Complex
When an operation involving a float operand and a complex number operand is executed, Python automatically converts the float into a complex number with an imaginary component of 0j. The outcome is consistently of complex data type.
Example:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor18022.setValue(decodedContent); // Set the default text
editor18022.clearSelection();
editor18022.setOptions({
maxLines: Infinity
});
function decodeHTML18022(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard18022() {
const code = editor18022.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor18022 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor18022 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
``````javascript
});
}
function hideOutput18022() {
var script = editor18022.getSession().getValue();
jQuery(".maineditor18022 .code-editor-output").hide();
}
// Assign event handlers to the buttons
document.getElementById("copyBtn18022").addEventListener("click", copyCodeToClipboard18022);
document.getElementById("runBtn18022").addEventListener("click", executeCode18022);
document.getElementById("closeoutputBtn18022").addEventListener("click", hideOutput18022);
Output:
Explanation: In this case, we incorporated complex and float data type operands. Consequently, the result was a complex data type.
3. Int and Complex
When an integer and a complex number serve as operands, Python automatically converts the integer data type into a complex data type by adding an imaginary part to the integer. The outcome of this operation is of the complex data type.
Example:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor78406.setValue(unescapedContent); // Define the default text
editor78406.clearSelection();
editor78406.setOptions({
maxLines: Infinity
});
function decodeHTML78406(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard78406() {
const code = editor78406.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
function hideOutput78406() {
var script = editor78406.getSession().getValue();
jQuery(".maineditor78406 .code-editor-output").hide();
}
// Assign event handlers to the buttons
document.getElementById("copyBtn78406").addEventListener("click", copyCodeToClipboard78406);
document.getElementById("runBtn78406").addEventListener("click", executeCode78406);
document.getElementById("closeoutputBtn78406").addEventListener("click", hideOutput78406);
Output:
Explanation: In this instance, we employed an integer and a complex number for multiplication. The resulting output was of the complex data type.
Conclusion
In this article, we examined Python arithmetic operators comprehensively. We tackled fundamental arithmetic actions such as addition and division, along with intricate ideas like precedence, associativity, and type conversion. We explored how Python conducts arithmetic operations using various data types like int, float, and complex numbers, focusing on implicit and explicit type conversions that ensure compatibility during Python computations. Grasping these mathematical principles lays a strong foundation for crafting more accurate and efficient code when engaging in real-world application projects.
To elevate your skills, consider enrolling in this Python training course for practical experience. Additionally, prepare for job interviews using Python interview questions curated by industry professionals.
Python Arithmetic Operators – FAQs
``````html
Q1. What are Python arithmetic operators?
These symbols instruct the interpreter to execute mathematical operations in Python.
Q2. What are the seven categories of operators in Python?
The seven Python operators include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//).
Q3. What does // signify in Python?
The // operator in Python is utilized for floor division, providing the nearest integer that is less than or equal to the result.
Q4. What occurs if I attempt to divide by zero in Python?
Python will raise a ZeroDivisionError.
Q5. How do the / and // operators differ in Python?
/ serves as a division operator, whereas // functions as a floor division operator.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.