🔢 Working with Numbers

Numbers are everywhere in programming! From counting items to calculating prices, from measuring distances to tracking scores—numbers are essential for making your programs useful and interactive.

Python makes working with numbers easy and powerful. It has two main number types: integers for whole numbers and floats for decimal numbers. Understanding both types helps you choose the right one for each situation.

# Basic number examples
age = 25           # Integer (whole number)
price = 19.99      # Float (decimal number)
temperature = -5   # Negative integer

print(f"Age: {age} (type: {type(age)})")
print(f"Price: ${price} (type: {type(price)})")
print(f"Temperature: {temperature}°C (type: {type(temperature)})")

🔢 Integer Numbers (int)

Integers are whole numbers—no decimal points allowed! They can be positive, negative, or zero. Python can handle incredibly large integers without any special setup, making them perfect for counting and precise calculations.

Use integers when you're working with things that can't be split into parts: people, books, days, years, etc.

# Working with integers
students = 30
books = 150
year = 2024

print(f"There are {students} students")
print(f"The library has {books} books")
print(f"Current year: {year}")

# Integers can be negative
score_change = -10
print(f"Score changed by: {score_change}")

➕ Integer Math

# Integer calculations
apples = 10
oranges = 15
total_fruit = apples + oranges

print(f"Apples: {apples}")
print(f"Oranges: {oranges}")
print(f"Total fruit: {total_fruit}")

# Python handles very large numbers automatically
population = 7800000000  # World population
print(f"World population: {population:,}")

🎯 Floating-Point Numbers (float)

Floats are numbers with decimal points—they represent precise values that need fractional parts. Perfect for measurements, prices, percentages, and scientific calculations.

Even if the decimal part is zero (like 42.0), Python still treats it as a float!

# Working with floats
height = 5.8
weight = 68.5
pi = 3.14159
price = 19.99

print(f"Height: {height} feet (type: {type(height)})")
print(f"Weight: {weight} kg (type: {type(weight)})")
print(f"Pi: {pi} (type: {type(pi)})")
print(f"Price: ${price} (type: {type(price)})")

⚡ Float vs Integer: The Key Difference

The difference between 5 and 5.0 is important in Python:

# The difference between 5 and 5.0
whole_number = 5      # Integer
decimal_number = 5.0  # Float

print(f"5 is type: {type(whole_number)}")
print(f"5.0 is type: {type(decimal_number)}")

# They're equal in value but different types
print(f"Are they equal? {whole_number == decimal_number}")
print(f"Same type? {type(whole_number) == type(decimal_number)}")

🧮 Basic Math Operations

Python supports all the math operations you'd expect, with some special behaviors depending on the number types:

# Basic math operations
a = 10
b = 3

print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")           # Always returns float!
print(f"Floor Division: {a} // {b} = {a // b}")    # Integer division
print(f"Remainder: {a} % {b} = {a % b}")           # Modulus
print(f"Power: {a} ** {b} = {a ** b}")             # Exponentiation

📦 Division Types

Python has two types of division—understanding both is important:

# Different types of division
total_items = 17
boxes = 3

regular_division = total_items / boxes      # Always returns float
floor_division = total_items // boxes       # Returns integer part
remainder = total_items % boxes             # Returns remainder

print(f"17 items in 3 boxes:")
print(f"Regular division: {regular_division}")  # 5.666...
print(f"Floor division: {floor_division}")      # 5 (whole boxes)
print(f"Remainder: {remainder}")                # 2 (items left over)

🔄 Converting Between Number Types

Sometimes you need to convert between integers and floats. Python provides built-in functions for this:

Converting with int() and float()

# Converting between types
decimal_number = 15.7
whole_number = 42

# Convert float to int (truncates!)
converted_int = int(decimal_number)
print(f"int(15.7) = {converted_int}")  # Removes decimal part

# Convert int to float
converted_float = float(whole_number)
print(f"float(42) = {converted_float}")  # Adds .0

Important: int() Truncates, Doesn't Round!

# int() removes decimal part (truncation)
print(f"int(15.7) = {int(15.7)}")    # 15 (not 16!)
print(f"int(15.2) = {int(15.2)}")    # 15
print(f"int(15.9) = {int(15.9)}")    # 15 (still not 16!)

# Use round() if you want rounding
print(f"round(15.7) = {round(15.7)}")  # 16

🛠️ Useful Number Functions

Python provides many built-in functions for working with numbers:

Absolute Values and Rounding

# abs() - absolute value (removes negative sign)
temperature = -15
distance = abs(temperature)
print(f"Temperature: {temperature}°C")
print(f"Distance from zero: {distance}")

# round() - rounds to nearest integer
price = 19.567
rounded_price = round(price, 2)  # Round to 2 decimal places
print(f"Original price: ${price}")
print(f"Rounded price: ${rounded_price}")

Finding Maximum and Minimum

# max() and min() - find largest and smallest
scores = [85, 92, 78, 96, 88]
highest = max(scores)
lowest = min(scores)

print(f"Scores: {scores}")
print(f"Highest score: {highest}")
print(f"Lowest score: {lowest}")

# Works with individual numbers too
print(f"Max of 5, 8, 3: {max(5, 8, 3)}")
print(f"Min of 5, 8, 3: {min(5, 8, 3)}")

Sum and Average

# sum() - adds up all numbers in a list
test_scores = [85, 92, 78, 96, 88]
total_points = sum(test_scores)
average_score = total_points / len(test_scores)

print(f"Test scores: {test_scores}")
print(f"Total points: {total_points}")
print(f"Average score: {average_score:.1f}")

Quick Number Practice 💪

Let's practice basic number operations with a simple exercise!

Hands-on Exercise

Practice working with numbers, math operations, and basic number functions.

python
# Number Practice - Keep it simple!

# Calculate a restaurant bill
meal_cost = 25.50
tax_rate = 0.08
tip_rate = 0.15

# Calculate tax and tip
tax = # TODO: Your code here (meal_cost * tax_rate)
tip = # TODO: Your code here (meal_cost * tip_rate)
total = # TODO: Your code here (meal_cost + tax + tip)

# Round the total to 2 decimal places
final_total = # TODO: Your code here (use round())

print(f"Meal: ${meal_cost}")
print(f"Tax: ${tax:.2f}")
print(f"Tip: ${tip:.2f}")
print(f"Total: ${final_total}")

Solution and Explanation 💡

Click to see the complete solution
# Number Practice - Simple solution

# Calculate a restaurant bill
meal_cost = 25.50
tax_rate = 0.08
tip_rate = 0.15

# Calculate tax and tip
tax = meal_cost * tax_rate       # 25.50 * 0.08 = 2.04
tip = meal_cost * tip_rate       # 25.50 * 0.15 = 3.825
total = meal_cost + tax + tip    # Add them all up

# Round the total to 2 decimal places
final_total = round(total, 2)    # Round to 2 decimal places

print(f"Meal: ${meal_cost}")
print(f"Tax: ${tax:.2f}")
print(f"Tip: ${tip:.2f}")
print(f"Total: ${final_total}")

Key Learning Points:

  • 📌 Multiplication: Used * for calculating percentages
  • 📌 Addition: Used + to add up the bill
  • 📌 round() function: Used round(total, 2) for 2 decimal places
  • 📌 F-string formatting: Used :.2f to display money nicely

🎨 Number Formatting for Display

Making numbers look good in your output is important for user-friendly programs:

# Basic number formatting
price = 1234.567
percentage = 0.8567

# Format to specific decimal places
formatted_price = f"${price:.2f}"      # 2 decimal places
formatted_percent = f"{percentage:.1%}" # 1 decimal place as percent

print(f"Price: {formatted_price}")
print(f"Success rate: {formatted_percent}")

# Large numbers with commas
population = 7800000000
formatted_pop = f"{population:,}"
print(f"World population: {formatted_pop}")

🔄 Common Number Patterns

Calculating Percentages

# Percentage calculations
total_students = 150
passed_students = 135

# Calculate percentage
pass_rate = (passed_students / total_students) * 100
print(f"Pass rate: {pass_rate:.1f}%")

# Calculate discount
original_price = 100
discount_percent = 15
discount_amount = original_price * (discount_percent / 100)
final_price = original_price - discount_amount

print(f"Original: ${original_price}")
print(f"Discount: {discount_percent}% (${discount_amount})")
print(f"Final price: ${final_price}")

Working with Averages

# Average calculations
monthly_sales = [12000, 15000, 18000, 14000, 16000]
total_sales = sum(monthly_sales)
average_sales = total_sales / len(monthly_sales)

print(f"Monthly sales: {monthly_sales}")
print(f"Average monthly sales: ${average_sales:,.2f}")

Temperature Conversions

# Temperature conversion formulas
celsius = 25
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15

print(f"{celsius}°C = {fahrenheit}°F = {kelvin}K")

# Convert Fahrenheit to Celsius
fahrenheit_temp = 77
celsius_temp = (fahrenheit_temp - 32) * 5/9
print(f"{fahrenheit_temp}°F = {celsius_temp:.1f}°C")

📖 Essential Number Functions Reference

FunctionPurposeExampleResult
abs(x)Absolute value (removes negative)abs(-5)5
round(x)Round to nearest integerround(3.7)4
round(x, n)Round to n decimal placesround(3.14159, 2)3.14
max(...)Find largest numbermax(5, 8, 3)8
min(...)Find smallest numbermin(5, 8, 3)3
sum(list)Sum numbers in a listsum([1, 2, 3, 4])10
int(x)Convert to integer (truncate)int(3.7)3
float(x)Convert to floatfloat(42)42.0

📋 Key Number Concepts Summary

ConceptExampleImportant Because
int vs float5 vs 5.0Different types for different uses
Division types/ vs //Regular vs integer division
Truncationint(15.7)15int() removes decimals, doesn't round
Roundinground(15.7)16Use round() when you want rounding
abs() functionabs(-5)5Removes negative signs
max/min functionsmax(5, 8, 3)8Find largest/smallest values

🧠 Test Your Knowledge

Ready to test your understanding of working with numbers in Python?

🚀 What's Next?

Excellent! You now have a solid understanding of Python's number types and how to work with them. Next, we'll explore another fundamental data type: text and strings.

Continue to: Text and Strings

You're mastering Python's building blocks! 🔢

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent