dotlinux blog

Working With Number Variables In Python

Numbers are the building blocks of programming, enabling everything from simple calculations to complex data analysis, scientific computing, and algorithm development. Python, known for its simplicity and versatility, provides robust support for numeric data types, making it easy to work with integers, decimals, and even complex numbers. Whether you’re a beginner learning the basics or an experienced developer diving into data science, understanding how to work with number variables in Python is essential.

In this blog, we’ll explore the core concepts of number variables in Python, including their types, how to create and manipulate them, perform operations, handle conversions, and leverage built-in tools for advanced calculations. By the end, you’ll have a solid foundation to tackle numeric tasks in Python with confidence.

2026-01

Table of Contents#

  1. Types of Number Variables in Python
    • Integers (int)
    • Floating-Point Numbers (float)
    • Complex Numbers (complex)
  2. Creating Number Variables
  3. Basic Operations on Number Variables
    • Arithmetic Operations
    • Comparison Operations
    • Assignment Operators
  4. Type Conversion Between Numbers
  5. Common Numeric Functions and Modules
    • Built-in Functions
    • The math Module
    • The statistics Module (Brief Overview)
  6. Handling Large Numbers
  7. Best Practices for Working With Number Variables
  8. Conclusion
  9. References

Types of Number Variables in Python#

Python supports three primary numeric types, each designed for specific use cases:

1. Integers (int)#

Integers are whole numbers without a decimal point, including positive, negative, and zero. Python integers have arbitrary precision, meaning they can be as large as your system’s memory allows (no fixed size limit, unlike some other languages like C++ or Java).

Examples:

age = 25          # Positive integer  
temperature = -5  # Negative integer  
zero = 0          # Zero  
large_number = 10**100  # A very large integer (1 followed by 100 zeros)  

Python also supports octal (base-8), hexadecimal (base-16), and binary (base-2) integers using prefixes:

  • Octal: Prefix with 0o (e.g., 0o12 = 10 in decimal).
  • Hexadecimal: Prefix with 0x (e.g., 0xFF = 255 in decimal).
  • Binary: Prefix with 0b (e.g., 0b1010 = 10 in decimal).

2. Floating-Point Numbers (float)#

Floating-point numbers (or “floats”) represent numbers with decimal points, including both rational and irrational values. They are stored using the IEEE 754 double-precision standard (64 bits), which provides about 15-17 significant digits of precision.

Examples:

pi = 3.14159       # Decimal float  
gravity = 9.8      # Positive float  
negative_float = -0.0001  # Negative float  
scientific_notation = 2.5e3  # 2.5 * 10^3 = 2500.0  

⚠️ Note: Floats have limited precision due to their binary representation. This can lead to unexpected results with decimal fractions. For example:

print(0.1 + 0.2)  # Output: 0.30000000000000004 (not exactly 0.3)  

We’ll discuss how to handle this later in Best Practices.

3. Complex Numbers (complex)#

Complex numbers have two parts: a real part and an imaginary part (denoted by j or J). They are useful in engineering, physics, and advanced mathematics.

Examples:

z1 = 3 + 4j       # Real part: 3, Imaginary part: 4  
z2 = 2.5 - 1j     # Mixed real/imaginary types  
z3 = complex(5)   # Shorthand: (5 + 0j)  

To access the real and imaginary parts of a complex number, use the .real and .imag attributes:

print(z1.real)  # Output: 3.0  
print(z1.imag)  # Output: 4.0  

Creating Number Variables#

In Python, variables are created by assigning a value using the = operator. Python is dynamically typed, so you don’t need to declare the type of the variable explicitly—it is inferred from the value.

Rules for Naming Variables:

  • Names can contain letters, numbers, and underscores (_), but cannot start with a number.
  • Names are case-sensitive (ageAge).
  • Avoid reserved keywords (e.g., if, for, def).

Examples of Creating Number Variables:

# Integers  
student_count = 45  
year = 2024  
 
# Floats  
height = 1.75  # in meters  
weight = 68.5  # in kilograms  
 
# Complex numbers  
signal = 10 + 2j  

Basic Operations on Number Variables#

Python supports a wide range of operations for manipulating number variables. Let’s break them down:

Arithmetic Operations#

These operations perform mathematical calculations.

OperationSymbolDescriptionExampleResult
Addition+Sum of two numbers5 + 38
Subtraction-Difference of two numbers10 - 46
Multiplication*Product of two numbers7 * 214
Division/Quotient (returns float)15 / 43.75
Floor Division//Quotient rounded down to nearest integer15 // 43
Modulus%Remainder after division15 % 43
Exponentiation**Power (e.g., a**b = a^b)2** 38

Examples:

a = 10  
b = 3  
 
print(a + b)   # 13  
print(a / b)   # 3.3333333333333335 (float)  
print(a // b)  # 3 (floor division)  
print(a % b)   # 1 (remainder)  
print(a** b)  # 1000 (10^3)  

⚠️ Note: For negative numbers, // rounds down (toward negative infinity), not just truncates:

print(-10 // 3)  # Output: -4 (since -4 * 3 = -12 ≤ -10)  

Comparison Operations#

These operations compare two numbers and return a boolean (True or False).

OperationSymbolDescriptionExampleResult
Equal==Are the values equal?5 == 5True
Not Equal!=Are the values different?5 != 3True
Greater Than>Left > Right?7 > 2True
Less Than<Left < Right?7 < 2False
Greater Than or Equal>=Left ≥ Right?5 >= 5True
Less Than or Equal<=Left ≤ Right?3 <= 1False

Examples:

x = 7  
y = 7  
 
print(x == y)  # True  
print(x > y)   # False  
print(x <= y)  # True  

Assignment Operators#

These operators combine arithmetic operations with assignment to simplify code.

OperatorShorthand ForExampleEquivalent To
+=a = a + ba += 5a = a + 5
-=a = a - ba -= 3a = a - 3
*=a = a * ba *= 2a = a * 2
/=a = a / ba /= 4a = a / 4
//=a = a // ba //= 2a = a // 2
%=a = a % ba %= 3a = a % 3
**=a = a **ba**= 3a = a **3

Example:

count = 5  
count += 3  # count = count + 3 → count becomes 8  
print(count)  # 8  
 
price = 100  
price *= 0.9  # price = price * 0.9 → 90.0 (10% discount)  
print(price)  # 90.0  

Type Conversion Between Numbers#

Python allows converting between numeric types using built-in functions: int(), float(), and complex().

Converting to Integer (int())#

  • Converts a float to an integer by truncating toward zero (e.g., int(3.9)3, int(-2.8)-2).
  • Converts a complex number to an integer only if the imaginary part is zero (e.g., int(5+0j)5; otherwise, it raises a TypeError).

Examples:

print(int(4.7))       # 4 (truncates decimal part)  
print(int("10"))      # 10 (converts numeric string to int)  
print(int(5 + 0j))    # 5 (complex with 0 imaginary part)  

Converting to Float (float())#

  • Converts an integer to a float by adding .0 (e.g., float(7)7.0).
  • Converts a complex number to a float only if the imaginary part is zero (e.g., float(3+0j)3.0).

Examples:

print(float(5))       # 5.0  
print(float("3.14"))  # 3.14 (converts numeric string to float)  
print(float(2 + 0j))  # 2.0  

Converting to Complex (complex())#

  • Converts an integer or float to a complex number with a zero imaginary part (e.g., complex(4)(4+0j), complex(3.14)(3.14+0j)).

Examples:

print(complex(6))     # (6+0j)  
print(complex(2.5))   # (2.5+0j)  
print(complex(3, 4))  # (3+4j) (real=3, imaginary=4)  

Common Numeric Functions and Modules#

Python provides built-in functions and modules to simplify advanced numeric tasks.

Built-in Functions#

FunctionDescriptionExampleResult
abs(x)Returns the absolute value of xabs(-7)7
round(x, n)Rounds x to n decimal places (default n=0)round(3.1415, 2)3.14
max(x1, x2, ...)Returns the largest valuemax(2, 5, 1)5
min(x1, x2, ...)Returns the smallest valuemin(2, 5, 1)1
sum(iterable)Returns the sum of elements in an iterable (e.g., list)sum([1, 2, 3])6

Examples:

print(abs(-10))          # 10  
print(round(2.5))        # 2 (rounds to nearest even integer for .5 cases)  
print(max(10, 20, 5))    # 20  
print(sum([2, 4, 6]))    # 12  

The math Module#

The math module provides advanced mathematical functions (e.g., trigonometry, logarithms, constants). To use it, first import the module:

import math  

Common math Functions:

FunctionDescriptionExampleResult
math.piMathematical constant π (~3.14159)math.pi3.141592653589793
math.eMathematical constant e (~2.71828)math.e2.718281828459045
math.sqrt(x)Square root of xmath.sqrt(16)4.0
math.sin(x)Sine of x (radians)math.sin(math.pi/2)1.0
math.log(x, base)Logarithm of x with given base (default base=e)math.log(100, 10)2.0
math.floor(x)Largest integer ≤ xmath.floor(3.8)3
math.ceil(x)Smallest integer ≥ xmath.ceil(3.2)4

Example:

import math  
 
print(math.sqrt(25))      # 5.0  
print(math.sin(math.pi))  # 1.2246467991473532e-16 (approximately 0)  
print(math.log(math.e))   # 1.0  

The statistics Module (Brief Overview)#

For statistical calculations (e.g., mean, median, standard deviation), use the statistics module:

import statistics  
 
data = [2, 4, 6, 8, 10]  
print(statistics.mean(data))    # 6.0 (average)  
print(statistics.median(data))  # 6 (middle value)  

Handling Large Numbers#

Python natively supports arbitrarily large integers, so you can work with numbers as big as your system’s memory allows. For example:

large_int = 10**1000  # 1 followed by 1000 zeros  
print(large_int)      # Outputs the full number (no overflow!)  

For very large floating-point numbers, Python uses scientific notation to avoid clutter:

large_float = 1.23e100  # 1.23 * 10^100  
print(large_float)      # 1.23e+100  

Best Practices for Working With Number Variables#

1.** Use Descriptive Variable Names : Choose names like total_price or average_score instead of x or y to improve readability.
2.
Be Cautious With Float Precision **: Due to binary representation, avoid direct equality checks for floats. Use round() or a tolerance (e.g., abs(a - b) < 1e-9) instead:

a = 0.1 + 0.2  
b = 0.3  
print(a == b)          # False (due to precision)  
print(round(a, 1) == b)  # True (rounded to 1 decimal place)  

3.** Prefer // Over int() for Division : Use a // b instead of int(a / b) for floor division, as it handles negative numbers more predictably.
4.
Use Underscores for Readability : For large numbers, separate digits with underscores (e.g., 1_000_000 instead of 1000000).
5.
Leverage Built-in Modules **: Use math for advanced math and statistics for stats instead of reinventing the wheel.

Conclusion#

Number variables are the backbone of numeric computing in Python. By mastering integers, floats, and complex numbers, along with operations, conversions, and built-in tools like the math module, you’ll be equipped to solve a wide range of problems—from simple calculations to advanced scientific computing. Remember to handle float precision carefully and follow best practices to write clean, efficient code.

References#