beginner

Python Numbers and Math

Master numeric data types and mathematical operations in Python.

Numbers are fundamental to programming. Python provides powerful numeric types including integers, floating-point numbers, and complex numbers. Whether you are building a calculator, analyzing data, or creating games, understanding how to work with numbers is essential. This exercise will teach you the core mathematical operations and numeric conversions that every Python developer needs to know.

📚 Concepts & Theory

Python Numeric Types:

  • Integers (int): Whole numbers without decimals
age = 25
count = -10
big_number = 1_000_000  # Underscore for readability
  • Floating-point (float): Numbers with decimals
price = 19.99
pi = 3.14159
scientific = 2.5e-3  # 0.0025

Mathematical Operators:

  • + Addition

  • - Subtraction

  • * Multiplication

  • / Division (always returns float)

  • // Floor division (rounds down)

  • % Modulo (remainder)

  • Exponentiation
Type Conversion:
int(3.7)    # Returns 3
float(5) # Returns 5.0
str(42) # Returns "42"

Useful Math Functions:**

abs(-5)      # Absolute value: 5
round(3.7) # Rounds to nearest: 4
max(1, 5, 3) # Maximum: 5
min(1, 5, 3) # Minimum: 1

🎯 Your Challenge

Calculate the area of a rectangle with width 7.5 and height 4. Store the result in a variable called `area`. Then calculate the perimeter and store it in `perimeter`.

📝 Starter Code

Python
# Rectangle dimensions
width = 7.5
height = 4

# Calculate area (width * height)
area = 

# Calculate perimeter (2 * (width + height))
perimeter = 
  • Area formula: width * height
  • Perimeter formula: 2 * (width + height)
  • Use parentheses to control order of operations
  • Python follows standard math operator precedence

Solution

Python
width = 7.5
height = 4

area = width * height

perimeter = 2 * (width + height)

Explanation

The area of a rectangle is calculated by multiplying width by height (7.5 * 4 = 30.0). The perimeter is the sum of all sides, which equals 2 times the sum of width and height (2 * (7.5 + 4) = 23.0). Python automatically handles the float result from multiplying an integer with a float.

⚠️ Common Mistakes to Avoid

  • Forgetting parentheses in perimeter formula
  • Using wrong operator for multiplication
  • Confusing integer and float division
  • Not understanding operator precedence

❓ Frequently Asked Questions

In Python 3, the / operator always returns a float, even when dividing two integers. Use // for floor division if you want an integer result.
The / operator performs true division and returns a float. The // operator performs floor division, rounding down to the nearest integer.

🔗 Related Concepts