Python Numbers
Master numeric data types and mathematical operations in Python
🔢 Understanding Numbers
Python has three built-in numeric data types that handle different kinds of numerical values. Understanding these types is essential for mathematical operations, data analysis, and scientific computing.
# Integer example
x = 42
print(x) # Output: 42
# Float example
y = 3.14
print(y) # Output: 3.14
3
Number Types
Dynamic
Typing
Powerful
Operations
Number Types in Python
Python has three built-in numeric data types:
int (Integer)
Whole numbers, positive or negative
42
-17
0
float (Floating Point)
Decimal numbers
3.14
-2.5
0.0
complex (Complex)
Numbers with real and imaginary parts
3+4j
2-1j
5j
Working with Integers
Integer Examples
# Integer variables
age = 25
temperature = -10
score = 0
big_number = 1000000
# Python can handle very large integers
huge_number = 123456789012345678901234567890
print(huge_number) # No overflow errors!
# Check the type
print(type(age)) #
print(type(big_number)) #
# Integer operations
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a // b) # Floor division: 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000
Real-World Example: Age Calculator
# Age calculator program
current_year = 2024
birth_year = 1995
# Calculate age
age = current_year - birth_year
print(f"You are {age} years old")
# Calculate age in different units
age_in_months = age * 12
age_in_days = age * 365 # Approximate
age_in_hours = age_in_days * 24
print(f"That's approximately:")
print(f" {age_in_months} months")
print(f" {age_in_days} days")
print(f" {age_in_hours:,} hours") # Comma separator for readability
Working with Floats
Float Examples
# Float variables
price = 19.99
pi = 3.14159
temperature = -2.5
scientific = 2.5e4 # Scientific notation: 25000.0
# Check the type
print(type(price)) #
print(type(scientific)) #
# Float operations
a = 10.5
b = 3.2
print(a + b) # Addition: 13.7
print(a - b) # Subtraction: 7.3
print(a * b) # Multiplication: 33.6
print(a / b) # Division: 3.28125
print(a // b) # Floor division: 3.0
print(a % b) # Modulus: 0.8999999999999995
# Rounding floats
result = a / b
print(f"Exact: {result}")
print(f"Rounded to 2 decimals: {round(result, 2)}")
print(f"Rounded to nearest integer: {round(result)}")
Real-World Example: Shopping Cart Total
# Shopping cart calculation
item1_price = 12.99
item2_price = 8.50
item3_price = 25.75
# Calculate subtotal
subtotal = item1_price + item2_price + item3_price
print(f"Subtotal: ${subtotal:.2f}")
# Apply tax (8.5%)
tax_rate = 0.085
tax_amount = subtotal * tax_rate
print(f"Tax (8.5%): ${tax_amount:.2f}")
# Calculate total
total = subtotal + tax_amount
print(f"Total: ${total:.2f}")
# Apply discount if total > $40
if total > 40:
discount = total * 0.10 # 10% discount
final_total = total - discount
print(f"Discount (10%): -${discount:.2f}")
print(f"Final Total: ${final_total:.2f}")
else:
print(f"Final Total: ${total:.2f}")
Working with Complex Numbers
Complex Number Examples
# Complex number creation
z1 = 3 + 4j
z2 = complex(2, -1) # 2 - 1j
z3 = 5j # Pure imaginary
print(f"z1 = {z1}") # (3+4j)
print(f"z2 = {z2}") # (2-1j)
print(f"z3 = {z3}") # 5j
# Access real and imaginary parts
print(f"Real part of z1: {z1.real}") # 3.0
print(f"Imaginary part of z1: {z1.imag}") # 4.0
# Complex number operations
result = z1 + z2
print(f"z1 + z2 = {result}") # (5+3j)
result = z1 * z2
print(f"z1 * z2 = {result}") # (10+5j)
# Complex conjugate
print(f"Conjugate of z1: {z1.conjugate()}") # (3-4j)
# Absolute value (magnitude)
import math
magnitude = abs(z1)
print(f"Magnitude of z1: {magnitude}") # 5.0
Number Conversion
Converting Between Number Types
# Converting to int
float_num = 3.14
string_num = "42"
bool_val = True
print(int(float_num)) # 3 (truncates decimal)
print(int(string_num)) # 42
print(int(bool_val)) # 1 (True = 1, False = 0)
# Converting to float
int_num = 42
string_float = "3.14"
print(float(int_num)) # 42.0
print(float(string_float)) # 3.14
# Converting to complex
real_num = 5
print(complex(real_num)) # (5+0j)
print(complex(3, 4)) # (3+4j)
# Be careful with conversions!
try:
result = int("3.14") # This will cause an error
except ValueError as e:
print(f"Error: {e}")
# Correct way: convert to float first, then int
result = int(float("3.14"))
print(f"Correct conversion: {result}") # 3
Mathematical Operations
Basic Operations
+
Addition
5 + 3 = 8
-
Subtraction
5 - 3 = 2
*
Multiplication
5 * 3 = 15
/
Division
5 / 3 = 1.667
Advanced Operations
//
Floor Division
5 // 3 = 1
%
Modulus
5 % 3 = 2
**
Exponentiation
5 ** 3 = 125
abs()
Absolute Value
abs(-5) = 5
Real-World Example: Loan Calculator
# Simple loan payment calculator
principal = 10000.0 # Loan amount
annual_rate = 0.05 # 5% annual interest rate
years = 3 # Loan term in years
# Convert annual rate to monthly
monthly_rate = annual_rate / 12
num_payments = years * 12
# Calculate monthly payment using formula
# M = P * [r(1+r)^n] / [(1+r)^n - 1]
if monthly_rate > 0:
monthly_payment = principal * (
monthly_rate * (1 + monthly_rate) ** num_payments
) / (
(1 + monthly_rate) ** num_payments - 1
)
else:
monthly_payment = principal / num_payments
print(f"Loan Details:")
print(f" Principal: ${principal:,.2f}")
print(f" Annual Rate: {annual_rate:.1%}")
print(f" Term: {years} years")
print(f" Monthly Payment: ${monthly_payment:.2f}")
# Calculate total paid and interest
total_paid = monthly_payment * num_payments
total_interest = total_paid - principal
print(f"\nSummary:")
print(f" Total Paid: ${total_paid:,.2f}")
print(f" Total Interest: ${total_interest:,.2f}")
print(f" Interest as % of Principal: {(total_interest/principal):.1%}")
Built-in Math Functions
Common Math Functions
# Built-in functions
numbers = [1, -5, 3.14, -2.7, 10]
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}") # 6.44
print(f"Min: {min(numbers)}") # -5
print(f"Max: {max(numbers)}") # 10
print(f"Length: {len(numbers)}") # 5
# Individual number functions
x = -4.7
print(f"Absolute value of {x}: {abs(x)}") # 4.7
print(f"Rounded {x}: {round(x)}") # -5
print(f"Rounded to 1 decimal: {round(x, 1)}") # -4.7
# Power and roots
base = 2
exponent = 8
print(f"{base} to the power of {exponent}: {pow(base, exponent)}") # 256
print(f"Square root of 16: {16 ** 0.5}") # 4.0
Using the Math Module
import math
# Constants
print(f"Pi: {math.pi}") # 3.141592653589793
print(f"E: {math.e}") # 2.718281828459045
# Trigonometric functions (angles in radians)
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
print(f"Sin(45°): {math.sin(angle_radians):.3f}") # 0.707
print(f"Cos(45°): {math.cos(angle_radians):.3f}") # 0.707
print(f"Tan(45°): {math.tan(angle_radians):.3f}") # 1.000
# Logarithms
print(f"Natural log of e: {math.log(math.e)}") # 1.0
print(f"Log base 10 of 100: {math.log10(100)}") # 2.0
print(f"Log base 2 of 8: {math.log2(8)}") # 3.0
# Other useful functions
print(f"Square root of 25: {math.sqrt(25)}") # 5.0
print(f"Ceiling of 4.3: {math.ceil(4.3)}") # 5
print(f"Floor of 4.7: {math.floor(4.7)}") # 4
print(f"Factorial of 5: {math.factorial(5)}") # 120
🏋️ Practice Exercise: Number Calculator
Create a simple calculator that performs basic operations on two numbers:
Basic Calculator Challenge
# Simple calculator program
def calculate(num1, num2, operation):
"""Perform basic math operations on two numbers."""
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
return num1 / num2 if num2 != 0 else "Error: Division by zero"
else:
return "Invalid operation"
# Test the calculator
num1 = 10
num2 = 5
print(f"Numbers: {num1} and {num2}")
print(f"Addition: {calculate(num1, num2, '+')}")
print(f"Subtraction: {calculate(num1, num2, '-')}")
print(f"Multiplication: {calculate(num1, num2, '*')}")
print(f"Division: {calculate(num1, num2, '/')}")
# Try it yourself!
# x = float(input("Enter first number: "))
# y = float(input("Enter second number: "))
# op = input("Enter operation (+,-,*,/): ")
# print(f"Result: {calculate(x, y, op)}")