Arithmetic Operations

Basic Arithmetic

  1. # addition
  2. 10 + 5
  3. #ans: 15
  4. #ans: subtraction
  5. 10 - 5
  6. #ans: 5
  7. #ans: multiplication
  8. 10 * 5
  9. #ans: 50

Division Operations

  1. # division (always returns float)
  2. 10 / 5
  3. #ans: 2.0
  4. 10 / 3
  5. #ans: 3.3333...
  6. #ans: floor division
  7. 10 // 3
  8. #ans: 3

Modulus

  1. # modulus (remainder)
  2. 10 % 3
  3. #ans: 1
  4. 7 % 3
  5. #ans: 1
  6. 15 % 4
  7. #ans: 3

Exponentiation

  1. # power/exponentiation
  2. 10 ** 2
  3. #ans: 100
  4. 2 ** 3
  5. #ans: 8
  6. 5 ** 0
  7. #ans: 1

Operator Precedence

  1. # PEMDAS rules apply
  2. 10 + 5 * 2
  3. #ans: 20 (multiply first)
  4. (10 + 5) * 2
  5. #ans: 30 (parentheses first)
  6. 2 + 3 * 4
  7. #ans: 14

Exercises - Part 1

  1. # what is the result?
  2. 7 % 3
  3. #ans: 1
  4. #ans: division types
  5. 10 / 3
  6. #ans: 3.3333...
  7. 10 // 3
  8. #ans: 3

Exercises - Part 2

  1. # negative modulus?
  2. -10 % 3
  3. #ans: 2
  4. # what is this?
  5. 2 ** 3 ** 2
  6. #ans: 512 (right associative: 2^(3^2) = 2^9)

Exercises - Part 3

  1. # operator precedence?
  2. 10 + 5 * 2
  3. #ans: 20
  4. # what happens?
  5. 5 / 0
  6. #ans: ZeroDivisionError

Exercises - Part 4

  1. # floor division with negative?
  2. -10 // 3
  3. #ans: -4
  4. # modulus with float?
  5. 10.5 % 3
  6. #ans: 1.5

Exercises - Part 5

  1. # what is result?
  2. 100 // 10
  3. #ans: 10
  4. # power of zero?
  5. 5 ** 0
  6. #ans: 1
  7. # negative exponent?
  8. 2 ** -1
  9. #ans: 0.5

Exercises - Part 6

  1. # order of operations?
  2. 2 * 3 ** 2
  3. #ans: 18 (exponent first)
  4. # mixing operations?
  5. 10 - 5 + 3
  6. #ans: 8 (left to right)
  7. # division by float?
  8. 10 / 2.0
  9. #ans: 5.0

Google tag (gtag.js)