Python Number Data Type
In Python, numbers are one of the most commonly used types of data. Whether you're counting items, performing calculations, or working with measurements, you'll need to store and manipulate numbers in your programs.
Python handles numbers through specific number data types, which define how a value is stored and what kind of operations can be performed on it.
There are three main number data types in Python - int , float , complex . Each type is suited for specific tasks, and Python automatically assigns the correct type based on the value you provide.
So let's Understand this number data types which is important because they affect how data is processed and what operations are allowed.
Table of Content
- Why Use Number Data Types?
- Overview of Python Numeric Types
- Integer (int) Data Type
- Definition and Characteristics
- Examples and Usage
- Large Integers and Underscores
- Floating-Point (float) Data Type
- Definition and Characteristics
- Examples and Usage
- Scientific Notation
- Special Float Values
- Complex (complex) Data Type
- Definition and Characteristics
- Examples and Usage
- Operations With Complex Numbers
- Type Checking and Conversion in Python
- Using type()
- Converting Between Numeric Types
- Numeric Operations in Python
- Arithmetic Operations
- Built-in Functions
- Real-World DevOps Use Case of Numeric Data Types
- Common Mistakes and Best Practices
So Why Use Number Data Types ?
- Mathematical Operations: Perform calculations, comparisons, and data analysis.
- Data Storage: Store numeric information such as age, price, temperature, or systems data.
- Precision and Performance: Choose the right type for accuracy and memory efficiency.
Overview of Python Numeric Types
Python provides three primary numeric data types:
- Integer (int): Whole numbers, positive or negative, without decimals.
- Floating-point (float): Numbers with decimal points or in exponential notation.
- Complex (complex): Numbers with real and imaginary parts.
All numeric types are objects in Python and can be checked or converted using Python built-in functions.
Integer (int) Data Type
Definition and Characteristics
- Integers represent whole numbers, both positive and negative, including zero.
- In Python, integers have unlimited precision, meaning they can be arbitrarily large (limited only by available memory).
- No fractional or decimal component.
Examples and Usage
x = 10 y = -300 z = 0 print(type(x)) print(type(y)) print(type(z))
Output :
<class 'int'> <class 'int'> <class 'int'>
Integers are used for counting, indexing, and situations where only whole numbers make sense (e.g., number of items, year). Here type() function is a built-in Python function that tells us the data type of variables - x , y , z .
Large Integers and Underscores
Python allows underscores for readability in large numbers -
population = 1_400_000_000 print(population) # Output: 1400000000
Floating-Point (float) Data Type
Definition and Characteristics
- Floats represent real numbers with decimal points or in scientific notation.
- They can be positive or negative and are accurate up to 15 decimal places.
- Used when precision with fractions is required (e.g., measurements, prices).
Examples and Usage
a = 3.14159 b = -0.001 c = 0.0 print(type(a)) print(type(b)) print(type(c))
Output :
<class 'float'> <class 'float'> <class 'float'>
Scientific Notation
Floats can use exponential (scientific) notation with e or E -
x = 1e6 # 1,000,000.0 y = 2.5e-4 # 0.00025 print(x, y) print(type(x))
Output :
1000000.0 0.00025
<class 'float'>
Special Float Values
Python supports special float values like infinity and NaN (Not a Number) :
positive_inf = float('inf') negative_inf = float('-inf') not_a_number = float('nan') print(f"positive_inf - {positive_inf}, negative_inf - {negative_inf}, not_a_number - {not_a_number}")
Output :
positive_inf - inf, negative_inf - -inf, not_a_number - nan
You can also convert strings to floats, including scientific notation and special values :
print(float('1e3')) # Output: 1000.0 print(float('-Infinity')) # Output: -inf print(float('inf')) # Output: inf
Complex (complex) Data Type
Definition and Characteristics
- Complex numbers contain a real part and an imaginary part (e.g., a + bj).
- The imaginary part is denoted with a j (not i as in mathematics).
- Used in scientific, engineering, and mathematical computations.
Examples and Usage
z1 = 2 + 3j z2 = -1.5 + 0j z3 = 0 - 2j print(type(z1)) print(z1, z2, z3)
Output :
<class 'complex'>
z1 - (2+3j), z2 - (-1.5+0j), z3 - -2j
You must use j or J for the imaginary component, not i .
Operations With Complex Numbers
Python supports arithmetic with complex numbers :
a = 2 + 3j b = 1 - 4j print(a + b) print(a * b) print(abs(a))
Output :
(3-1j)
(14-5j)
3.605551275463989
You can access real and imaginary parts:
z = 5 + 6j print(z.real) # Output: 5.0 print(z.imag) # Output: 6.0
Type Checking and Conversion in Python
Using type()
To check a variable’s type, use the built-in type() function :
x = 42 print(type(x)) # <class 'int'>
y = 3.14 print(type(y)) # <class 'float'>
z = 1 + 2j print(type(z)) # <class 'complex'>
Converting Between Numeric Types
Python provides constructor functions for type conversion :
# int to float a = float(5) print(a) # Output: 5.0 # float to int (truncates decimal) b = int(5.99) print(b) # Output: 5 # int or float to complex c = complex(3) d = complex(2.5, -1) print(c) # Output: (3+0j) print(d) # Output: (2.5-1j)
You can also convert strings to numbers if the string represents a valid number:
num = int("123") flt = float("456.789") cmp = complex("7+8j") print(num, flt, cmp)
Numeric Operations in Python
Arithmetic Operations
Python supports all standard arithmetic operations on numeric types :
a = 10 b = 3 print(a + b) # Addition: 13 print(a - b) # Subtraction: 7 print(a * b) # Multiplication: 30 print(a / b) # Division: 3.333... print(a // b) # Floor division: 3 print(a % b) # Modulus: 1 print(a ** b) # Exponentiation: 1000
Built-in Python Functions Commonly Used with Number Data Types
Few we have already seen like int() , float() , complex() , type() and even print() function. So now let's see some others functions especially useful for DevOps engineers, automation scripters, and Python learners :-
round() – Rounds a Number
Usage: Rounds a float to the nearest integer or to a specific number of decimal places.
print(round(3.14159, 2)) # Output: 3.14
Why it's useful: Formatting output or reducing precision in metrics.
Usage: Returns the smallest or largest number from a list or group.
response_times = [120, 89, 135, 98] print(min(response_times)) # Output: 89 print(max(response_times)) # Output: 135
Why it's useful: Identifying thresholds, outliers, or best/worst performing metrics.
sum() – Add All Values in a List
Usage: Sums up all numbers in an iterable.
requests_per_minute = [120, 150, 100, 130] print(sum(requests_per_minute)) # Output: 500
Why it's useful: Reporting totals, usage summaries, or trend aggregation.
Use case: Let’s say you're building a CLI tool to summarize server CPU loads :
cpu_usages = [45.5, 67.8, 56.2, 89.1] average = round(sum(cpu_usages) / len(cpu_usages), 2) min_usage = min(cpu_usages) max_usage = max(cpu_usages) print(f"Average CPU: {average}%, Min: {min_usage}%, Max: {max_usage}%")
Output :
Average CPU: 64.65%, Min: 45.5%, Max: 89.1%
✔ This script uses: sum(), len(), round(), min(), and max() — all core functions with number types!
Real-World DevOps Use Case of Python Numeric Data Types
Python Number Data Types for DevOps Engineers helps a lot in DevOps automation, monitoring, and scripting tasks.
1. Resource Monitoring: Parsing and Aggregating System Metrics
Scenario:
Suppose you are writing a Python script to parse CPU and memory usage from system commands and calculate averages for reporting.
# Simulated output from system monitoring cpu_usages = ["23.5", "27.8", "19.6", "35.2"] # as strings from command output # Convert to float for calculation cpu_usages_float = [float(val) for val in cpu_usages] average_cpu = sum(cpu_usages_float) / len(cpu_usages_float) print(f"Average CPU Usage: {average_cpu:.2f}%")
# Output: Average CPU Usage: 26.53%
Explanation: DevOps scripts often need to convert string outputs from tools like ps, top, or docker stats into floats for aggregation and alerting. Interviewers may ask this as how to handle such type conversions in real monitoring scripts.
2. Disk Space Checks and Alerts
Scenario:
Suppose you need to check if available disk space (in GB) falls below a critical threshold and trigger an alert.
disk_free_gb = 7.4 # float, could come from parsing `df -h` output threshold_gb = 10 # int if disk_free_gb < threshold_gb: print("Warning: Low disk space!")
# Output: Warning: Low disk space!
Explanation: Mixing int and float in comparisons is common when automating infrastructure health checks.
3. Automated Log Analysis: Counting Error Occurrences
Scenario:
Count the number of error lines in a log file—a classic use of integers in DevOps automation.
error_count = 0 with open("app.log") as log_file: for line in log_file: if "ERROR" in line: error_count += 1 print("Total errors found:", error_count)
# Output: Total errors found: 17
Explanation: Integers are essential for counters in log parsing, a frequent DevOps scripting task.
4. Calculating Uptime Percentage
Scenario:
Given total uptime and downtime (in seconds as integers), calculate and format the uptime percentage.
total_time = 86400 # 1 day in seconds downtime = 360 # 6 minutes downtime uptime_percentage = ((total_time - downtime) / total_time) * 100 print(f"Uptime: {uptime_percentage:.2f}%")
# Output: Uptime: 99.58%
Explanation: Combining int and float for availability metrics is a standard DevOps reporting requirement.
5. Network Throughput Calculation
Scenario:
Suppose you receive network data in bytes and need to convert it to megabytes per second for dashboard display.
bytes_transferred = 10485760 # 10 MB in bytes (int) seconds = 5 # int mbps = (bytes_transferred / (1024 * 1024)) / seconds print(f"Network Throughput: {mbps:.2f} MB/s")
# Output: Network Throughput: 2.00 MB/s
Explanation: Unit conversion using integer and float arithmetic is routine in DevOps dashboards and monitoring tools.
6. Parsing and Validating Configuration Values
Scenario:
In many cases you have to read a YAML or JSON config file and need to ensure that numeric values (like port numbers or timeouts) are valid integers.
config = {"port": "8080", "timeout": "30"} try: port = int(config["port"]) timeout = int(config["timeout"]) if not (0 < port < 65536): raise ValueError("Invalid port number") except ValueError as e: print("Configuration error:", e)
Explanation: Validating and converting configuration values is critical for robust DevOps automation.
7. Interview Question: Calculate Rolling Average of Response Times
Scenario:
Given a stream of response times (floats), calculate the rolling average over the last N requests.
from collections import deque response_times = [0.23, 0.31, 0.27, 0.35, 0.29] window_size = 3 window = deque(maxlen=window_size) for rt in response_times: window.append(rt) avg = sum(window) / len(window) print(f"Rolling average ({len(window)}): {avg:.3f}")
Output :
Rolling average (1): 0.230 Rolling average (2): 0.270 Rolling average (3): 0.270 Rolling average (3): 0.310 Rolling average (3): 0.303
Explanation: This is a classic DevOps interview question —processing metrics in real time using numeric types and built-in data structures.
-> deque (double-ended queue) is imported from Python's collections module.
Why use deque?
- It allows fast appends and pops from both ends.
- Here, we used it with a fixed size (maxlen), so old values are dropped automatically.
That means at any time, we only keep the last 3 response times to calculate the rolling average.
deque(maxlen=3) will automatically drop the oldest value once it reaches 3 elements.
Understanding number data types in Python is an important aspects in real-world domains like automation, DevOps, data processing, and backend development.
So we learned the different types of numbers — integers, floats, and complex numbers — and how Python handles them with flexibility and simplicity with type conversion, built-in numeric functions, and real-world use cases like rolling averages, system monitoring, and calculations.