Math Operations & Functions
Math Operations
Integers +, -, *, /
Integers are whole numbers (positive, negative, or zero) without decimals.
print(type(2 + 4)) # Output: <class 'int'>
print(2 - 4)
print(2 * 4)
print('*' * 5) # Output: *****
print(*[1,2,3]) # Output: unpacks or separate
Float /
Floats are numbers with decimal points.
print(2 / 4) # Output: 0.5 (float division)
print(type(10.0))
Exponentiation **, Floor Division //, Modulus %
Exponentiation (**) raises a number to a power. Floor division (//) returns the integer part of division. Modulus (%) returns the remainder.
print(2 ** 4) # Output: 16 (2 raised to power 4)
print(4 // 2) # Output: 2 (floor division)
print(5 % 2) # Output: 1 (modulus)
Math Functions
round() rounds to the nearest integer. abs() returns the absolute value.
print(round(3.6)) # Output: 4 (rounds to nearest integer)
print(abs(-4)) # Output: 4 (absolute value)
Operators Precedence
print(2 + 3 * 4) # Output: 14 (multiplication before addition)
print((2 + 3) * 4) # Output: 20 (parentheses change precedence)
print((20 - 3) + 2 ** 2)
First precedence [Parentheses ()] Second precedence [Exponentiation *] Third precedence [Multiplication , Division /, Floor D //, Modulus %] Fourth precedence [Addition, Subtraction]
Complex Numbers
Complex numbers have a real and imaginary part.
print(2 + 3j) # Output: (2+3j)
Binary Representation
bin() converts integers to binary. int(..., 2) converts binary strings back to integers.
print(bin(10)) # Output: 0b1010 (binary representation of 10)
print(int('0b1010', 2)) # Output: 10 (convert binary string to integer)