Numbers are essential when writing any Python program. They allow you to perform calculations, represent data, index sequences like lists and strings, generate random values, and much more. In this comprehensive guide, we will dive deep into numeric types and arithmetic in Python.
We will cover key topics like:
Table of Contents
Open Table of Contents
Overview of Numeric Data Types
Python has two builtin numeric types - integers and floating-point numbers. These allow you to work with mathematical and quantified data in your code.
Integers
Integers (or ints) represent whole numbers like -2, 0, 25, 1000.
x = 10
print(type(x)) # Prints <class 'int'>
In Python 3, integers can be arbitrarily large in magnitude, limited only by your system’s memory and architecture. While the language supports unlimited size integers, very large values will still have practical limits.
Integers can be specified in decimal, binary, octal, or hexadecimal notation:
decimal = 109 # Base 10 decimal
binary = 0b1101011 # Base 2 binary
octal = 0o173 # Base 8 octal
hexadecimal = 0x21AB3F # Base 16 hexadecimal
Typical uses of integers include counting, loop counters, random numbers, and integer-based math.
Floating-Point Numbers
Floats represent real numbers with fractional precision, for example -2.5, 3.14159, or 5.0. The decimal point indicates a float value.
y = 2.5
print(type(y)) # Prints <class 'float'>
Floats provide up to 15-16 digits of precision. However, due to their binary representation, floats have limited precision and may introduce small rounding errors.
Common uses of floats involve measurements, probabilities, percentages, and values requiring fractional precision. Floats are vital for scientific computing and analysis.
Arithmetic Operations
Python includes a rich set of built-in arithmetic operations: addition, subtraction, multiplication, division, exponentiation, and modulus operations. These allow you to perform mathematical calculations in your programs.
Addition
The addition operator (+) sums two numbers:
print(5 + 2) # Prints 7
Subtraction
The subtraction operator (-) subtracts the right operand from the left:
print(10 - 3) # Prints 7
Multiplication
The multiplication operator (*) multiplies two numbers:
print(3 * 6) # Prints 18
Division
Division (/) divides the left operand by the right:
print(16 / 4) # Prints 4.0
Note that dividing two integers will return a float to avoid truncation.
Exponentiation
Exponentiation (**) raises a number to a power:
print(3 ** 4) # Prints 81
Modulus
The modulus operator (%) computes the remainder from dividing the left number by the right:
print(14 % 3) # Prints 2
Modulus is useful for constraining values to a range, wrapping, and more.
Order of Operations
Python follows the standard PEMDAS order of operations. You can use parentheses to override the default order and force operations to run in the desired sequence.
Type Conversion and Coercion
Since Python is dynamically typed, it handles implicit and explicit conversion between types frequently. This helps add flexibility to the language.
Implicit Type Conversion
Python will automatically convert between types when needed during operations. For example:
x = 5 # int
y = 2.5 # float
result = x + y # Implicitly converts x to float
print(result) # Prints 7.5
print(type(result)) # Prints <class 'float'>
The integer was implicitly coerced to a float to retain precision.
Explicit Type Conversion
You can use built-in functions to explicitly convert between types:
- int() - Construct integer from string, float, etc.
- float() - Construct float from string, integer, etc.
- str() - Create string representation from object
a = 5.4 # float
b = int(a) # Explicitly convert to int
print(b) # Prints 5
print(type(b)) # Prints <class 'int'>
x = 10 # int
y = str(x) # Explicitly convert to string
print(y) # Prints '10'
print(type(y)) # Prints <class 'str'>
Explicit conversion provides control over the process.
Type Coercion
In Python, type coercion refers to the automatic conversion of an object from one type to another to avoid errors during operations.
For example, passing an integer to a function expecting a float will coerce the int to a float:
def divide(a, b):
return a / b
x = 10 # int
y = 4
result = divide(x, y) # x coerced to float
print(result) # Prints 2.5
Here are some other examples where type coercion occurs:
- Adding an integer to a string coerces the int to str
- Comparing ints and floats converts the int to a float
- Passing a float to an integer parameter converts it to int
Coercion allows flexibility but can result in hidden bugs if types change unexpectedly. For readability and performance, prefer explicit conversion when possible.
Practical Examples and Use Cases
Let’s now look at some practical examples of how Python developers use numeric types and arithmetic.
Secure Password Hashing
Proper password hashing is important for secure authentication. The example below is overly simplified. Real implementations should use a cryptographic library like bcrypt
or hashlib
:
import hashlib
username = 'myuser'
password = 'password123'
# Insecure hashing omitted for simplicity
hash_value = hashlib.sha256(password.encode()).hexdigest()
print(hash_value)
Random Number Generation
The random
module generates pseudorandom numbers, commonly used in games, simulations, AI, and security:
import random
random_int = random.randint(1,10) # Random integer 1-10
random_float = random.random() # Random float 0.0-1.0
print(random_int)
print(random_float)
Calculating the Average
Floats provide the needed decimal precision to find averages:
values = [88, 92, 79, 93, 85]
total = sum(values)
length = len(values)
average = total / length
print(average) # Prints 87.4
Averages help analyze data in statistics and data science.
Formatting Monetary Values
When working with money, we can format floats as currency strings:
item_cost = 5.2
tax_rate = 0.075
tax_amount = item_cost * tax_rate
total = item_cost + tax_amount
print("Item: ${:.2f}".format(item_cost)) # Item: $5.20
print("Tax: ${:.2f}".format(tax_amount)) # Tax: $0.39
print("Total: ${:.2f}".format(total)) # Total: $5.59
This nicely formats currency for users.
Conclusion
In this comprehensive guide, we covered:
- Core numeric types like integers and floats
- Mathematical and arithmetic operations
- Type conversion and coercion
- Practical use cases and applications
You should now feel comfortable using numbers in your Python code to perform calculations, represent data, index sequences, generate random values, and more!
The concepts provided here form the foundation for using Python in data science, analytics, finance, science, and many other numeric computing fields.