Operations with Numbers

Operations

In Python, various operators are used to perform mathematical operations on numbers. Here’s a breakdown of the common operators and their usage:

OperatorMeaningExampleOutput
+Addition1 + 12
-Subtraction1 - 10
*Multiplication1 * 11
/True Division (returns a float)9 / 51.8
//Floor Division (integer division)9 // 51
**Exponentiation (power)2 ** 38
%Modulo (remainder of division)10 % 31

Key Concepts of Number Operations in Python

  • Addition (+): Adds two numbers together and returns the sum.

    result = 5 + 3  # Output: 8
    
  • Subtraction (-): Subtracts the second number from the first and returns the difference.

    result = 10 - 4  # Output: 6
    
  • Multiplication (*): Multiplies two numbers and returns the product.

    result = 7 * 6  # Output: 42
    
  • True Division (/): Divides the first number by the second, always returning a float.

    result = 9 / 4  # Output: 2.25
    
  • Floor Division (//): Divides the first number by the second and returns the largest integer less than or equal to the result.

    result = 9 // 4  # Output: 2
    
  • Exponentiation (**): Raises the first number to the power of the second number and returns the result.

    result = 3 ** 4  # Output: 81
    
  • Modulo (%): Returns the remainder of the division of the first number by the second number.

    result = 10 % 3  # Output: 1
    
  • Combination of Operations: Python supports combining multiple operations in a single expression, with standard precedence rules.

    result = (2 + 3) * (5 ** 2) / 4  # Output: 31.25
    
  • Order of Operations: Python follows the standard order of operations (PEMDAS/BODMAS) where Parentheses/Brackets, Exponents/Orders, Multiplication and Division, and Addition and Subtraction are performed in that order.

    result = 3 + 2 * (8 / 4) ** 2  # Output: 11.0
    
  • Type Conversion: Operations between different numeric types (e.g., integer and float) result in a float. Explicit type conversion can be performed using int(), float(), etc.

    int_result = int(7 / 3)  # Output: 2
    float_result = float(7 // 3)  # Output: 2.0