In Python, numbers are a basic data type used for mathematical operations. Python provides several types of numeric data:
Types of Numeric Data
- Integer (int)
Represents whole numbers. No limit to the size of an integer (limited by memory).
Example:x = 10 # Positive integer y = -5 # Negative integer z = 0 # Zero
- Floating Point (float)
Represents real numbers with decimal points. Includes scientific notation.
Example:pi = 3.14 # Floating point e = 2.718 # Another floating point sci = 1.23e4 # Scientific notation (1.23 × 10⁴) small = 1.2e-3 # Scientific notation (1.2 × 10⁻³)
- Complex Numbers (complex)
Represented as a + bj, where a is the real part, and b is the imaginary part.
Example:comp = 2 + 3j print(comp.real) # Output: 2.0 (real part) print(comp.imag) # Output: 3.0 (imaginary part)
Type Checking
You can check the type of a number using the type() function:
x = 10
y = 3.14
z = 1 + 2j
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'complex'>
Type Conversion
Python allows conversion between numeric types.
- Convert to Integer (int)
- Removes the fractional part (truncation).
Example:print(int(3.14)) # Output: 3 print(int(-2.99)) # Output: -2
- Convert to Float (float)
- Converts integers or strings to floating-point numbers.
Example:print(float(5)) # Output: 5.0 print(float("3.14")) # Output: 3.14
- Convert to Complex (complex)
- Converts numbers to complex type.
Example:print(complex(2)) # Output: (2+0j) print(complex(2, 3)) # Output: (2+3j)
Mathematical Operations
Python supports standard arithmetic operations: Operator Operation Example Result
Operator | Operation | Example | Result |
+ | Addition | 5 + 3 | 8 |
– | Subtraction | 10 – 4 | 6 |
* | Multiplication | 2 * 3 | 6 |
/ | Division (float) | 7 / 2 | 3.5 |
// | Floor Division | 7 // 2 | 3 |
% | Modulus (Remainder) | 7 % 2 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Special Functions for Numbers
Python provides several built-in functions for numeric operations:
abs(): Absolute value
print(abs(-5)) # Output: 5
round(): Round a float to a specified number of decimal places
print(round(3.14159, 2)) # Output: 3.14
pow(): Power (equivalent to **)
print(pow(2, 3)) # Output: 8
divmod(): Returns quotient and remainder as a tuple
print(divmod(7, 2)) # Output: (3, 1)
Using the math Module
Python’s math module provides advanced mathematical functions:
import math
print(math.sqrt(16)) # Output: 4.0 (square root)
print(math.factorial(5)) # Output: 120 (5!)
print(math.sin(math.pi/2)) # Output: 1.0 (sine of 90°)
print(math.log(10, 10)) # Output: 1.0 (logarithm base 10)
Random Numbers
Python’s random module can generate pseudo-random numbers:
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.uniform(1.0, 5.0)) # Random float between 1.0 and 5.0
print(random.choice([1, 2, 3])) # Randomly select from a list