Python Arithmetic Operators

Arithmetic Operators in Python

Basic Arithmetic Operators

  • Python's arithmetic operators largely follow standard mathematical rules.

  • Addition: Uses the plus sign ++.

  • Subtraction: Uses the minus sign -.

  • Multiplication: Uses the asterisk sign *.

  • Division: Uses the forward slash //.

Order of Operations

  • Python adheres to the mathematical order of operations.

  • Example: Multiplication happens before addition.

  • Parentheses can be used to override the default order.

Exponentiation

  • The exponentiation operator is represented by two asterisks: **$.

  • Example: 3**2calculates3tothepowerof2,resultingin9.</p></li></ul><h4collapsed="false"seolevelmigrated="true">BitwiseXOROperator</h4><ul><li><p>Thecaretsigncalculates 3 to the power of 2, resulting in 9.</p></li></ul><h4 collapsed="false" seolevelmigrated="true">Bitwise XOR Operator</h4><ul><li><p>The caret sign^is<strong>not</strong>forexponentiation;itsabitwiseXORoperator.</p></li><li><p>BitwiseXORisanarithmeticoperatorthatdoesntfollowstandardmathematicalrules.</p></li><li><p>Itsnotcoveredinthiscourse,butfurtherinformationisavailableinthenotes.</p></li><li><p>Important:Usingis <strong>not</strong> for exponentiation; it's a bitwise XOR operator.</p></li><li><p>Bitwise XOR is an arithmetic operator that doesn't follow standard mathematical rules.</p></li><li><p>It's not covered in this course, but further information is available in the notes.</p></li><li><p>Important: Using^insteadofinstead of** for exponentiation can lead to unexpected results.

Modulo Operator

  • Represented by the percent sign %.

  • Returns the remainder after division.

  • Example: 99 % 2 (nine modulo two) results in 1 because 9 divided by 2 is 4 with a remainder of 1.

Integer Division

  • Denoted by two forward slashes: //$.

  • Divides one integer by another and rounds the result down to the nearest integer.

  • Example: 7 // 2(sevenintegerdividedbytwo)resultsin3,because7dividedby2is3.5,whichisroundeddownto3.</p></li><li><p>Roundingbehavior:Integerdivisionroundsdownevenfornegativenumbers.</p></li><li><p>Example:(seven integer divided by two) results in 3, because 7 divided by 2 is 3.5, which is rounded down to 3.</p></li><li><p>Rounding behavior: Integer division rounds down even for negative numbers.</p></li><li><p>Example:-7 // 2$$ (negative seven integer divided by two) results in -4, because -3.5 is rounded down to -4.

Other Operator Categories

  • There are other categories of operators in Python that will be covered later.