Prerequisites
- Basic understanding of programming concepts ๐
- Python installation (3.8+) ๐
- VS Code or preferred IDE ๐ป
What you'll learn
- Understand the concept fundamentals ๐ฏ
- Apply the concept in real projects ๐๏ธ
- Debug common issues ๐
- Write clean, Pythonic code โจ
๐ฏ Introduction
Welcome to this exciting tutorial on working with numbers in Python! ๐ In this guide, weโll explore the magical world of integers, floats, and complex numbers.
Youโll discover how Pythonโs number types can transform your programming experience. Whether youโre building financial applications ๐ฐ, scientific calculations ๐ฌ, or games ๐ฎ, understanding numbers is essential for writing powerful Python code.
By the end of this tutorial, youโll feel confident working with all types of numbers in your own projects! Letโs dive in! ๐โโ๏ธ
๐ Understanding Numbers in Python
๐ค What are Pythonโs Number Types?
Pythonโs number types are like different tools in a toolbox ๐งฐ. Think of them as specialized instruments: integers for counting whole things (like people ๐ฅ), floats for measuring (like temperature ๐ก๏ธ), and complex numbers for advanced math (like electrical engineering โก).
In Python terms, we have three main numeric types. This means you can:
- โจ Count and calculate with whole numbers (int)
- ๐ Work with decimals and fractions (float)
- ๐ก๏ธ Handle advanced mathematical operations (complex)
๐ก Why Different Number Types?
Hereโs why Python offers different number types:
- Precision Matters ๐ฏ: Different calculations need different precision
- Memory Efficiency ๐ป: Use only what you need
- Mathematical Accuracy ๐: Some operations require specific types
- Real-world Modeling ๐ง: Match the type to your data
Real-world example: Imagine building a shopping cart ๐. Youโd use integers for item quantities (canโt buy 2.5 shirts!), floats for prices ($19.99), and maybe complex numbers for advanced analytics.
๐ง Basic Syntax and Usage
๐ Working with Integers
Letโs start with the basics:
# ๐ Hello, integers!
age = 25 # ๐ Your age in years
items_in_cart = 3 # ๐ Number of items
score = 1000 # ๐ฎ Game score
# ๐จ Integer operations
total_items = items_in_cart + 5 # โ Addition
remaining_lives = 3 - 1 # โ Subtraction
double_score = score * 2 # โ๏ธ Multiplication
teams = 20 // 4 # โ Floor division (5 teams)
print(f"You have {remaining_lives} lives left! ๐")
๐ก Explanation: Notice how integers are perfect for counting discrete things! No decimals needed.
๐ฏ Working with Floats
Hereโs how to work with decimal numbers:
# ๐๏ธ Float examples
price = 19.99 # ๐ฐ Product price
temperature = 98.6 # ๐ก๏ธ Body temperature
pi = 3.14159 # ๐ฅง Mathematical constant
# ๐จ Float operations
total_cost = price * 3 # 59.97
celsius = (temperature - 32) * 5/9 # 37.0
circle_area = pi * (5 ** 2) # 78.54 (radius = 5)
# ๐ Mixing integers and floats
discount = price * 0.2 # 20% off = 3.998
final_price = price - discount # 15.992
print(f"Final price: ${final_price:.2f} ๐ธ") # Rounds to 2 decimals
๐ Working with Complex Numbers
For the mathematically adventurous:
# ๐ Complex numbers (real + imaginary)
z1 = 3 + 4j # ๐ฏ 3 is real, 4j is imaginary
z2 = complex(2, -1) # ๐จ Another way to create: 2-1j
# ๐ง Complex operations
sum_z = z1 + z2 # (5+3j)
product = z1 * z2 # (10+5j)
# ๐ Accessing parts
real_part = z1.real # 3.0
imaginary_part = z1.imag # 4.0
magnitude = abs(z1) # 5.0 (distance from origin)
print(f"Complex magic: {z1} has magnitude {magnitude} โจ")
๐ก Practical Examples
๐ Example 1: Smart Shopping Calculator
Letโs build a real shopping calculator:
# ๐๏ธ Shopping calculator with different number types
class SmartCart:
def __init__(self):
self.items = [] # ๐ฆ List of items
self.tax_rate = 0.08 # ๐ฐ 8% tax (float)
def add_item(self, name, quantity, price):
# ๐ฏ Quantity must be integer, price can be float
if not isinstance(quantity, int) or quantity < 1:
print(f"โ Can't add {quantity} {name}s!")
return
item = {
'name': name,
'quantity': quantity, # ๐ข Integer
'price': price, # ๐ต Float
'emoji': self._get_emoji(name)
}
self.items.append(item)
print(f"โ
Added {quantity} {item['emoji']} {name}(s) @ ${price:.2f} each")
def _get_emoji(self, name):
# ๐จ Fun emoji mapping
emojis = {
'apple': '๐', 'banana': '๐', 'pizza': '๐',
'coffee': 'โ', 'book': '๐', 'game': '๐ฎ'
}
return emojis.get(name.lower(), '๐ฆ')
def calculate_total(self):
subtotal = 0.0 # ๐ฐ Start with float
print("\n๐ Your Cart:")
print("-" * 40)
for item in self.items:
item_total = item['quantity'] * item['price']
subtotal += item_total
print(f"{item['emoji']} {item['name']:.<20} "
f"{item['quantity']} x ${item['price']:.2f} = ${item_total:.2f}")
tax = subtotal * self.tax_rate
total = subtotal + tax
print("-" * 40)
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax (8%): ${tax:.2f}")
print(f"๐ฐ Total: ${total:.2f}")
return total
# ๐ฎ Let's go shopping!
cart = SmartCart()
cart.add_item("Apple", 5, 0.99) # ๐ 5 apples
cart.add_item("Pizza", 2, 12.99) # ๐ 2 pizzas
cart.add_item("Coffee", 1, 4.50) # โ 1 coffee
total = cart.calculate_total()
๐ฏ Try it yourself: Add a discount feature that applies percentage discounts to specific items!
๐ฎ Example 2: Physics Game Engine
Letโs make physics fun with numbers:
import math
# ๐โโ๏ธ Simple physics simulation
class PhysicsObject:
def __init__(self, name, x=0.0, y=0.0, mass=1.0):
self.name = name
self.x = x # ๐ Position (float)
self.y = y
self.vx = 0.0 # ๐ Velocity
self.vy = 0.0
self.mass = mass # โ๏ธ Mass (float)
self.emoji = "๐ฆ" # Default emoji
def apply_force(self, fx, fy, time=1.0):
# ๐ฏ F = ma, so a = F/m
ax = fx / self.mass
ay = fy / self.mass
# ๐ Update velocity: v = v0 + at
self.vx += ax * time
self.vy += ay * time
# ๐ Update position: x = x0 + vt
self.x += self.vx * time
self.y += self.vy * time
print(f"{self.emoji} {self.name} moved to ({self.x:.1f}, {self.y:.1f})")
def distance_to(self, other):
# ๐ Calculate distance using Pythagorean theorem
dx = self.x - other.x
dy = self.y - other.y
distance = math.sqrt(dx**2 + dy**2)
return distance
def has_collided(self, other, radius=1.0):
# ๐ฅ Check collision
return self.distance_to(other) < radius * 2
# ๐ฎ Create game objects
player = PhysicsObject("Player", x=0, y=0, mass=2.0)
player.emoji = "๐"
enemy = PhysicsObject("Enemy", x=10, y=10, mass=3.0)
enemy.emoji = "๐พ"
powerup = PhysicsObject("PowerUp", x=5, y=5, mass=0.5)
powerup.emoji = "โญ"
# ๐ Apply forces and simulate movement
print("๐ฎ Game Physics Demo!")
print("-" * 40)
player.apply_force(5, 5) # Move diagonally
enemy.apply_force(-3, -3) # Move toward player
# ๐ Check distances
print(f"\n๐ Distance to enemy: {player.distance_to(enemy):.1f}")
print(f"๐ Distance to powerup: {player.distance_to(powerup):.1f}")
if player.has_collided(powerup, radius=2.0):
print("โญ You got the power-up! ๐")
๐ Example 3: Financial Calculator with Complex Analysis
Advanced example using all number types:
# ๐ฐ Financial calculator with compound interest
class InvestmentCalculator:
def __init__(self):
self.investments = []
def add_investment(self, name, principal, rate, years, compounds_per_year=12):
investment = {
'name': name,
'principal': float(principal), # ๐ต Initial amount
'rate': float(rate) / 100, # ๐ Convert percentage
'years': int(years), # ๐
Time period
'n': int(compounds_per_year) # ๐ Compounding frequency
}
self.investments.append(investment)
def calculate_compound_interest(self, investment):
# ๐ A = P(1 + r/n)^(nt)
P = investment['principal']
r = investment['rate']
n = investment['n']
t = investment['years']
# ๐งฎ Using complex numbers for advanced calculations
compound_factor = complex(1 + r/n, 0)
exponent = n * t
# ๐ฐ Calculate final amount
amount = P * (compound_factor.real ** exponent)
interest = amount - P
return amount, interest
def analyze_all(self):
print("๐ผ Investment Analysis")
print("=" * 50)
total_invested = 0 # ๐ข Integer counter
total_returns = 0.0 # ๐ฐ Float for money
for inv in self.investments:
amount, interest = self.calculate_compound_interest(inv)
total_invested += int(inv['principal'])
total_returns += amount
print(f"\n๐ {inv['name']}:")
print(f" ๐ต Principal: ${inv['principal']:,.2f}")
print(f" ๐ Rate: {inv['rate']*100:.1f}%")
print(f" ๐
Years: {inv['years']}")
print(f" ๐ฐ Final Amount: ${amount:,.2f}")
print(f" โจ Interest Earned: ${interest:,.2f}")
print(f" ๐ Return: {(interest/inv['principal']*100):.1f}%")
print("\n" + "=" * 50)
print(f"๐ผ Total Invested: ${total_invested:,}")
print(f"๐ฐ Total Returns: ${total_returns:,.2f}")
print(f"โจ Total Profit: ${(total_returns - total_invested):,.2f}")
# ๐ฏ Let's invest!
calc = InvestmentCalculator()
calc.add_investment("Savings Account", 10000, 2.5, 5, 12)
calc.add_investment("Stock Portfolio", 25000, 8.5, 10, 4)
calc.add_investment("Crypto Fund", 5000, 15.0, 3, 365)
calc.analyze_all()
๐ Advanced Concepts
๐งโโ๏ธ Number Type Conversions
When youโre ready to level up, master type conversions:
# ๐ฏ Advanced type conversions
class NumberWizard:
@staticmethod
def demonstrate_conversions():
# ๐ Basic conversions
float_num = 3.14159
int_num = int(float_num) # 3 (truncates, doesn't round!)
# ๐จ Smart rounding
rounded = round(float_num, 2) # 3.14
rounded_int = round(float_num) # 3
# ๐ String to number conversions
price_string = "19.99"
price_float = float(price_string) # 19.99
quantity_string = "42"
quantity_int = int(quantity_string) # 42
# ๐ซ Binary, octal, hexadecimal
binary_num = 0b1010 # 10 in decimal
octal_num = 0o12 # 10 in decimal
hex_num = 0xA # 10 in decimal
# ๐ฏ Complex conversions
complex_from_string = complex("3+4j") # (3+4j)
print(f"โจ Float {float_num} โ Int {int_num}")
print(f"๐ฏ Binary {bin(10)} = Octal {oct(10)} = Hex {hex(10)}")
# ๐ช Try the magic!
wizard = NumberWizard()
wizard.demonstrate_conversions()
๐๏ธ Arbitrary Precision and Special Values
For the brave developers:
# ๐ Working with very large numbers and special values
import decimal
import math
class AdvancedNumbers:
@staticmethod
def explore_limits():
# ๐ Python integers have unlimited precision!
huge_number = 10 ** 100 # 1 googol
even_bigger = huge_number ** 10 # Mind-blowing!
print(f"๐ A googol has {len(str(huge_number))} digits!")
# ๐ฐ Decimal precision for money
decimal.getcontext().prec = 4 # Set precision
price = decimal.Decimal('19.99')
tax = decimal.Decimal('0.08')
total = price * (1 + tax) # Exact decimal math!
print(f"๐ต Exact total: ${total}")
# ๐ฏ Special float values
infinity = float('inf')
negative_infinity = float('-inf')
not_a_number = float('nan')
print(f"โพ๏ธ Infinity + 1 = {infinity + 1}")
print(f"๐ค Is NaN equal to itself? {not_a_number == not_a_number}") # False!
# ๐ฌ Math constants
print(f"๐ฅง Pi = {math.pi}")
print(f"๐ e = {math.e}")
print(f"๐ Tau = {math.tau}") # 2ฯ
# ๐ฎ Explore the limits!
AdvancedNumbers.explore_limits()
โ ๏ธ Common Pitfalls and Solutions
๐ฑ Pitfall 1: Float Precision Issues
# โ Wrong way - float precision can surprise you!
total = 0.1 + 0.2
print(total == 0.3) # False! ๐ฑ
print(f"0.1 + 0.2 = {total}") # 0.30000000000000004
# โ
Correct way - use proper comparison!
import math
# Method 1: Use math.isclose()
result = 0.1 + 0.2
print(math.isclose(result, 0.3)) # True! โ
# Method 2: Use decimal for money
from decimal import Decimal
price1 = Decimal('0.10')
price2 = Decimal('0.20')
total = price1 + price2
print(total == Decimal('0.30')) # True! โ
๐คฏ Pitfall 2: Integer Division Confusion
# โ Dangerous - might not give expected result!
pizza_slices = 10
people = 3
slices_per_person = pizza_slices / people # 3.333...
# ๐ฑ Can't give someone 0.333 of a slice!
print(f"Each person gets {slices_per_person} slices")
# โ
Safe - use integer division!
slices_per_person = pizza_slices // people # 3
leftover = pizza_slices % people # 1
print(f"๐ Each person gets {slices_per_person} slices")
print(f"๐ {leftover} slice(s) left over!")
๐ฅ Pitfall 3: Type Mixing Errors
# โ Wrong - mixing strings and numbers
user_input = "42"
try:
result = user_input + 8 # ๐ฅ TypeError!
except TypeError as e:
print(f"โ Error: {e}")
# โ
Correct - convert first!
user_input = "42"
number = int(user_input) # Convert to int
result = number + 8 # 50
print(f"โ
Result: {result}")
# ๐ก๏ธ Even better - validate input!
def safe_add(user_input, number_to_add):
try:
num = float(user_input)
return num + number_to_add
except ValueError:
print(f"โ ๏ธ '{user_input}' is not a valid number!")
return None
result = safe_add("42.5", 7.5) # 50.0 โ
๐ ๏ธ Best Practices
- ๐ฏ Choose the Right Type: Use integers for counting, floats for measurements
- ๐ฐ Money Matters: Use Decimal for financial calculations
- ๐ก๏ธ Validate Input: Always check user input before converting
- ๐ Avoid Float Comparison: Use
math.isclose()
instead of==
- โจ Document Units: Always specify units in variable names (e.g.,
price_usd
,distance_km
)
๐งช Hands-On Exercise
๐ฏ Challenge: Build a Scientific Calculator
Create a calculator that handles different number types:
๐ Requirements:
- โ Basic operations (+, -, *, /, //, %, **)
- ๐ฌ Scientific functions (sqrt, sin, cos, log)
- ๐ฐ Financial mode with decimal precision
- ๐ Statistics mode (mean, median, mode)
- ๐จ Each mode should have its own emoji theme!
๐ Bonus Points:
- Add memory functions (M+, M-, MR, MC)
- Implement unit conversions
- Create a history feature
- Add complex number support
๐ก Solution
๐ Click to see solution
import math
import statistics
from decimal import Decimal, getcontext
# ๐ฏ Our multi-mode calculator!
class ScientificCalculator:
def __init__(self):
self.memory = 0
self.history = []
self.mode = "standard" # standard, scientific, financial, statistics
getcontext().prec = 10 # Set decimal precision
def set_mode(self, mode):
modes = {
"standard": "๐ข",
"scientific": "๐ฌ",
"financial": "๐ฐ",
"statistics": "๐"
}
if mode in modes:
self.mode = mode
print(f"{modes[mode]} Switched to {mode} mode!")
else:
print("โ Invalid mode!")
def calculate(self, operation, *args):
result = None
if self.mode == "standard":
result = self._standard_calc(operation, *args)
elif self.mode == "scientific":
result = self._scientific_calc(operation, *args)
elif self.mode == "financial":
result = self._financial_calc(operation, *args)
elif self.mode == "statistics":
result = self._statistics_calc(operation, *args)
if result is not None:
self.history.append(f"{operation}: {result}")
print(f"โจ Result: {result}")
return result
def _standard_calc(self, op, a, b=None):
ops = {
'add': lambda: a + b,
'subtract': lambda: a - b,
'multiply': lambda: a * b,
'divide': lambda: a / b if b != 0 else "โ Division by zero!",
'floor_divide': lambda: a // b if b != 0 else "โ Division by zero!",
'modulo': lambda: a % b if b != 0 else "โ Division by zero!",
'power': lambda: a ** b
}
if op in ops and b is not None:
return ops[op]()
else:
return "โ Invalid operation!"
def _scientific_calc(self, op, x):
ops = {
'sqrt': lambda: math.sqrt(x) if x >= 0 else "โ Can't sqrt negative!",
'sin': lambda: math.sin(math.radians(x)),
'cos': lambda: math.cos(math.radians(x)),
'tan': lambda: math.tan(math.radians(x)),
'log': lambda: math.log10(x) if x > 0 else "โ Can't log non-positive!",
'ln': lambda: math.log(x) if x > 0 else "โ Can't log non-positive!",
'factorial': lambda: math.factorial(int(x)) if x >= 0 else "โ No negative factorial!"
}
if op in ops:
return ops[op]()
else:
return "โ Invalid scientific operation!"
def _financial_calc(self, op, *args):
if op == 'compound_interest':
P, r, n, t = args
P = Decimal(str(P))
r = Decimal(str(r)) / 100
n = int(n)
t = int(t)
amount = P * (1 + r/n) ** (n*t)
return float(amount.quantize(Decimal('0.01')))
elif op == 'loan_payment':
P, r, n = args
P = Decimal(str(P))
r = Decimal(str(r)) / 100 / 12 # Monthly rate
n = int(n) * 12 # Total months
if r == 0:
return float(P / n)
payment = P * (r * (1 + r)**n) / ((1 + r)**n - 1)
return float(payment.quantize(Decimal('0.01')))
return "โ Invalid financial operation!"
def _statistics_calc(self, op, data):
if not data:
return "โ No data provided!"
ops = {
'mean': lambda: statistics.mean(data),
'median': lambda: statistics.median(data),
'mode': lambda: statistics.mode(data) if len(set(data)) < len(data) else "No mode",
'stdev': lambda: statistics.stdev(data) if len(data) > 1 else "Need more data",
'variance': lambda: statistics.variance(data) if len(data) > 1 else "Need more data"
}
if op in ops:
return ops[op]()
else:
return "โ Invalid statistics operation!"
def memory_add(self, value):
self.memory += value
print(f"๐พ Memory: {self.memory}")
def memory_clear(self):
self.memory = 0
print("๐๏ธ Memory cleared!")
def show_history(self):
print("\n๐ Calculation History:")
for calc in self.history[-5:]: # Show last 5
print(f" โข {calc}")
# ๐ฎ Test our calculator!
calc = ScientificCalculator()
# Standard mode
print("๐ข Standard Operations:")
calc.calculate('add', 10, 5)
calc.calculate('power', 2, 10)
# Scientific mode
print("\n๐ฌ Scientific Operations:")
calc.set_mode('scientific')
calc.calculate('sqrt', 16)
calc.calculate('sin', 30)
# Financial mode
print("\n๐ฐ Financial Calculations:")
calc.set_mode('financial')
# $10,000 at 5% for 10 years, compounded monthly
calc.calculate('compound_interest', 10000, 5, 12, 10)
# Statistics mode
print("\n๐ Statistics:")
calc.set_mode('statistics')
data = [23, 45, 67, 45, 89, 45, 23, 67, 78]
calc.calculate('mean', data)
calc.calculate('median', data)
calc.calculate('mode', data)
# Show history
calc.show_history()
๐ Key Takeaways
Youโve learned so much! Hereโs what you can now do:
- โ Work with integers, floats, and complex numbers with confidence ๐ช
- โ Avoid common precision and type errors that trip up beginners ๐ก๏ธ
- โ Apply number types correctly in real projects ๐ฏ
- โ Debug number-related issues like a pro ๐
- โ Build awesome calculations with Python! ๐
Remember: Choosing the right number type is like choosing the right tool for the job. Master them all, and youโll be unstoppable! ๐ค
๐ค Next Steps
Congratulations! ๐ Youโve mastered working with numbers in Python!
Hereโs what to do next:
- ๐ป Practice with the calculator exercise above
- ๐๏ธ Build a small project using different number types
- ๐ Move on to our next tutorial: String manipulation in Python
- ๐ Share your number wizardry with others!
Remember: Every Python expert started by counting from 0. Keep coding, keep calculating, and most importantly, have fun! ๐
Happy coding! ๐๐โจ