#!/usr/bin/python3 # -*- coding: utf-8 -*- # %% Numbers, mathematical operators # You have numbers 3 # => 3 # Math is what you would expect. # The following operators (actions) do NOT change their operands (objects) """ + Addition operator Adds values on either side of the operator. a + b = 31 """ 1 + 1 # => 2 """ - Subtraction operator Subtracts right hand operand from left hand operand. a - b = -11 """ 8 - 1 # => 7 """ * Multiplication operator Multiplies values on either side of the operator a * b = 210 """ 10 * 2 # => 20 """ / Division operator Divides left hand operand by right hand operand b / a = 2.1 """ 35 / 5 # => 7.0 # Integer division rounds down (truncates) # for both positive and negative numbers. """ // Floor / Int Division operator The division of operands where the result is the quotient, in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity): 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 """ 5 // 3 # => 1 -5 // 3 # => -2 5.0 // 3.0 # => 1.0 # works on floats too -5.0 // 3.0 # => -2.0 # The result of / division is always a float 10.0 / 3 # => 3.3333333333333335 4 / 2 # => 2.0 # Modulo operation a % b gives you the remainder of a / b """ % Modulus operator Divides left hand operand by right hand operand and returns remainder b % a = 1 """ 7 % 3 # => 1 6 % 3 # => 0 # Exponentiation (x ** y, x to the yth power) """ ** Exponent operator Performs exponential (power) calculation on operators a ** b = 10 to the power 20 """ 2 ** 0 2 ** 1 2 ** 2 2 ** 3 # => 8 2 ** 4 2 ** 5 2 ** 6 2 ** 7 2 ** 8 2 ** 9 2 ** 10 2 ** 11 2 ** 12 2 ** 13 2 ** 14 2 ** 15 2 ** 16 # It's likely worth memorizing these out to 16, and will come in handy. # Precedence # Enforce precedence with parentheses. # When () not needed, include them anyway! # Implicit: 1 + 3 * 2 # => 7 # Explicit: 1 + (3 * 2) # => 7 (1 + 3) * 2 # => 8 # Explicit is better than implicit, even when both are correct.