Python Numbers
Understanding Python Numbers
Section titled “Understanding Python Numbers”Numbers are a fundamental and versatile data type in Python, enabling a wide range of mathematical operations and computations. In Python, numbers can be categorized into integers, floating-point numbers, and complex numbers. Let’s explore these numeric data types and how they can be utilized in Python.
Integers
Section titled “Integers”Integers in Python are whole numbers, both positive and negative, without any decimal component. You can perform various arithmetic operations on integers, such as addition, subtraction, multiplication, and division.
a = 5
b = -10
result = a + b # Result is -5Python allows unlimited precision for integers, meaning they can be as large as your system’s memory allows.
big = 2 ** 100 # no overflow, Python handles huge integers
print(big) # 1267650600228229401496703205376Number Bases and Readable Literals
Section titled “Number Bases and Readable Literals”Integers can be written in binary, octal, and hexadecimal using prefixes, and you can group digits with underscores for readability (the underscores are ignored by Python):
binary = 0b1010 # binary -> 10
octal = 0o17 # octal -> 15
hexadecimal = 0xFF # hex -> 255
million = 1_000_000 # underscores aid reading -> 1000000
print(binary, octal, hexadecimal, million)
print(bin(10), oct(15), hex(255)) # convert back to base stringsOutput:
C:\Users\Your Name> python bases.py
10 15 255 1000000
0b1010 0o17 0xffFloating-Point Numbers
Section titled “Floating-Point Numbers”Floating-point numbers represent real numbers with a decimal point or in exponential form. They are used to handle both integer and fractional values.
pi = 3.14159
radius = 2.5
area = pi * (radius ** 2) # Calculating the area of a circleWhile floating-point numbers are powerful for scientific and mathematical computations, they may introduce precision issues due to the binary representation of real numbers.
The Floating-Point Precision Gotcha
Section titled “The Floating-Point Precision Gotcha”This surprises every beginner — floats are stored in binary, so some decimals cannot be represented exactly:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False!When exact decimal arithmetic matters (money, for example), use the decimal module:
from decimal import Decimal
price = Decimal("0.1") + Decimal("0.2")
print(price) # 0.3 (exact)Complex Numbers
Section titled “Complex Numbers”complex
Section titled “complex”Complex numbers have both a real and an imaginary part, represented as a + bj, where a and b are real numbers, and j is the imaginary unit.
z = 3 + 4jYou can perform operations like addition, subtraction, multiplication, and division on complex numbers.
w = 1 - 2j
result = z * w # Result is (11-2j)Numeric Operations
Section titled “Numeric Operations”Python supports a wide range of operations on numeric data types. Here are some common examples:
-
Arithmetic Operations:
numbers.py a = 10 b = 3 addition = a + b subtraction = a - b multiplication = a * b division = a / b -
Exponential Operation:
numbers.py square = 4 ** 2 # Result is 16 -
Modulo Operation:
numbers.py remainder = 10 % 3 # Result is 1
Numeric Comparisons
Section titled “Numeric Comparisons”In Python, you can compare numeric values using the following comparison operators:
a = 10
b = 5
print(a > b) # TruePython Number Casting
Section titled “Python Number Casting”You can convert numeric values from one data type to another using the following built-in functions:
int()- converts to an integerfloat()- converts to a floating-point numbercomplex()- converts to a complex number
num_int = 10
num_float = float(num_int) # Convert integer to float
num_complex = complex(num_int) # Convert integer to complexnum_float = 10.5
num_int = int(num_float) # Convert float to integer
num_complex = complex(num_float) # Convert float to complexnum_complex = 3 + 4j
num_int = int(num_complex) # Raises TypeError
num_float = float(num_complex) # Raises TypeErrornum_str = "42"
num_int = int(num_str) # Convert string to integer
num_float = float(num_str) # Convert string to float
num_complex = complex(num_str) # Convert string to complexMathematical Functions
Section titled “Mathematical Functions”Python’s math module provides a plethora of mathematical functions, including square root, logarithms, trigonometric functions, and more.
import math
sqrt_result = math.sqrt(25) # Result is 5.0Random Numbers
Section titled “Random Numbers”Python’s random module provides functions for generating random numbers. For example, you can use the random() function to generate a random floating-point number between 0 and 1.
import random
print(random.random()) # Prints a random number between 0 and 1
print(random.randrange(1, 10)) # Prints a random integer between 1 and 10Built-in Number Functions
Section titled “Built-in Number Functions”You do not always need the math module. Python has several handy built-ins for numbers:
print(abs(-7)) # 7 -> absolute value
print(round(3.14159, 2)) # 3.14 -> round to 2 decimals
print(pow(2, 8)) # 256 -> 2 to the power 8
print(divmod(17, 5)) # (3, 2) -> quotient and remainder together
print(max(3, 9, 1)) # 9
print(min(3, 9, 1)) # 1Augmented Assignment
Section titled “Augmented Assignment”Operators like +=, -=, *=, /=, //=, %=, and **= update a variable in place — a shorthand that keeps code concise:
count = 10
count += 5 # same as: count = count + 5
count *= 2 # same as: count = count * 2
count //= 3 # floor division assignment
print(count) # 10Visualize it
Section titled “Visualize it”Python groups all numeric values into three built-in types, each suited to a different kind of value.
flowchart TB
A["Numeric types"] --> B["int (whole numbers, unlimited size)"]
A --> C["float (decimals, 64-bit)"]
A --> D["complex (real + imaginary, e.g. 3 + 4j)"]
Conclusion
Section titled “Conclusion”Numbers in Python are a versatile and integral part of the language’s functionality. Whether you’re dealing with simple integer calculations or complex mathematical operations involving floating-point or complex numbers, Python provides a straightforward and expressive syntax. Understanding how to work with numbers is crucial for various applications, including scientific computing, data analysis, and algorithmic problem-solving.
As you continue your Python journey, explore the rich set of numeric operations and mathematical functions Python offers. Gain proficiency in leveraging numeric data types to solve diverse problems and unlock the full potential of numerical computing in Python.
For more in-depth tutorials and practical examples, check out our resources on Python Central Hub!
Try it: Numbers Exercises
Section titled “Try it: Numbers Exercises”Exercise 1 – Integer Arithmetic
Section titled “Exercise 1 – Integer Arithmetic”Exercise 2 – Float Operations
Section titled “Exercise 2 – Float Operations”Exercise 3 – Number Type Conversion
Section titled “Exercise 3 – Number Type Conversion”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading