Menu
Python Numeric Datatypes
In Python, numeric data types represent numbers and can be used for various mathematical operations. Here are the main numeric data types:
Integers (`int`):
-
- Integers are whole numbers without a fractional part.
age = 25
Floats (`float`):
-
- Floats represent real numbers with a decimal point or in scientific notation.
height = 5.9
Complex Numbers(`complex`):
-
- Complex numbers have a real and an imaginary part.
complex_number = 3 + 4j
Basic Numeric Operations:
- Arithmetic Operations:
a = 5
b = 2
# Addition
sum_result = a + b # Outputs: 7
# Subtraction
diff_result = a - b # Outputs: 3
# Multiplication
product_result = a * b # Outputs: 10
# Division
division_result = a / b # Outputs: 2.5
- Exponentiation and Modulus:
# Exponentiation
power_result = a ** b # Outputs: 25
# Modulus (remainder)
modulus_result = a % b # Outputs: 1
Type Conversion:
- You can convert between numeric data types using type conversion functions like int(), float(), and complex().
# Convert float to integer
x = int(5.9) # Outputs: 5
# Convert integer to float
y = float(42) # Outputs: 42.0
# Convert integer to complex
z = complex(3) # Outputs: (3+0j)
Dictionaries (`dict`):
-
- Key-value pairs, used to store data in a structured way.
person = {"name": "Alice", "age": 30, "city": "New York"}
Sets (`set`):
-
- Unordered collections of unique items.
unique_numbers = {1, 2, 3, 4, 5}
None Type (`NoneType`):
-
- Represents the absence of a value or a null value.
result = None
Type Conversion:
You can convert between different data types using functions like
int()
, float()
, str()
, etc.
# Convert float to integer
x = int(5.9) # Outputs: 5
# Convert integer to float
y = float(42) # Outputs: 42.0
# Convert integer to complex
z = complex(3) # Outputs: (3+0j)
Math Library:
Python provides a math library for more advanced mathematical functions.
import math
# Square root
sqrt_result = math.sqrt(25) # Outputs: 5.0
# Trigonometric functions
sin_result = math.sin(math.radians(30)) # Outputs: 0.49999999999999994
Understanding numeric data types and operations is crucial for performing mathematical calculations in Python. These types provide flexibility and precision for a wide range of applications, from basic arithmetic to complex scientific computations.