HomeCourseModule 03 › Numbers — ints, floats, and the math operators

Numbers — ints, floats, and the math operators

Module 03 · Variables and Data Types7 min readBeginner

What you'll learn

  • Distinguish ints from floats
  • Use Python's arithmetic operators including //, %, **
  • Round and format numeric output

Two flavours: int and float

int = a whole number: 0, 1, -42, 1_000_000.
float = a decimal number: 0.5, -3.14, 2.0.

You can check what kind a value is with type():

type(42)        # <class 'int'>
type(3.14)      # <class 'float'>
type(1_000_000) # <class 'int'>   underscores are legal as thousand-separators

The math operators

OperatorWhat it doesExampleResult
+Add3 + 47
-Subtract10 - 37
*Multiply5 * 630
/Divide (always returns a float)10 / 42.5
//Integer divide (drops the remainder)10 // 42
%Modulo (the remainder)10 % 42
**Power2 ** 101024

Two tricks worth knowing

Round to N decimals

round(3.14159, 2)   # 3.14
round(1234.5678, 0) # 1235.0

Format with commas and currency

total = 1234567.891
print(f"${total:,.2f}")     # $1,234,567.89

The f"..." string is called an f-string. We cover it properly in the next lesson; for now know that you can pop variables and format hints into one inside curly braces.

Integer vs float — when does it matter?

Mostly it doesn't. Python converts between them automatically. Two practical gotchas:

Walkthrough: split a bill three ways

Inputs

bill = 87.45
tip_pct = 18
people = 3

Compute

tip = bill * tip_pct / 100
total = bill + tip
per_person = total / people

Print neatly

print(f"Bill:       ${bill:,.2f}")
print(f"Tip ({tip_pct}%): ${tip:,.2f}")
print(f"Total:      ${total:,.2f}")
print(f"Per person: ${per_person:,.2f}")

Key takeaways

  • int = whole, float = decimal.
  • / always returns a float; // truncates; % gives the remainder.
  • round(x, 2) rounds; f"${x:,.2f}" formats with commas and two decimals.

Power-of-two table

Print the first ten powers of two in a column, like this:

2^1 = 2
2^2 = 4
2^3 = 8
...
2^10 = 1024

Hint: use a for loop (we cover those in Module 4) or just write ten lines.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.