CrackKit
0% complete
Python: Zero to Hero

Numbers, strings & f-strings

Numbers and strings are where you'll spend most of your early code. This lesson covers arithmetic, the string toolkit, and f-strings — the modern way to build text that you'll use in every program.

Arithmetic operators

python
7 + 2     # 9    addition
7 - 2     # 5    subtraction
7 * 2     # 14   multiplication
7 / 2     # 3.5  TRUE division — always returns a float
7 // 2    # 3    FLOOR division — rounds down to an int
7 % 2     # 1    modulo — the remainder
7 ** 2    # 49   exponent (7 squared)

Two beginner traps live here:

  • / always gives a float, even 4 / 22.0. Use // when you want an integer result.
  • % (modulo) is everywhere in real code: n % 2 == 0 tests even, i % len(arr) wraps an index around, n % 10 extracts the last digit.

Strings: the essentials

python
s = "Python"
len(s)            # 6      — length
s.upper()         # "PYTHON"
s.lower()         # "python"
s.replace("Py", "My")   # "Mython"
"  hi  ".strip()  # "hi"   — remove surrounding whitespace
"a,b,c".split(",")      # ["a", "b", "c"]
"-".join(["x","y"])     # "x-y"
"cat" in "concatenate"  # True   — substring test

Strings are immutable: methods like .upper() return a new string; they never change the original. s.upper() alone does nothing unless you capture it: s = s.upper().

Indexing and slicing

python
word = "PYTHON"
#        012345      (and negatives: -6-5-4-3-2-1)
word[0]      # "P"   — first character
word[-1]     # "N"   — last character
word[1:4]    # "YTH" — from index 1 up to (not including) 4
word[:3]     # "PYT" — start omitted = from the beginning
word[::2]    # "PTO" — every 2nd character
word[::-1]   # "NOHTYP" — reversed (a famous Python trick)

The slice rule [start:stop:step]stop is exclusive — is identical for lists (section 3), so learn it once here.

f-strings: building text

The modern, readable way to inject values into strings. Put f before the quote, then {expressions} inside:

python
name = "Ada"
age = 36
f"{name} is {age} years old"      # "Ada is 36 years old"
f"Next year: {age + 1}"           # "Next year: 37" — any expression works
f"{name!r}"                       # "'Ada'" — !r shows the repr (with quotes)

price = 1234.5678
f"₹{price:.2f}"                   # "₹1234.57" — 2 decimal places
f"{price:,.2f}"                  # "1,234.57" — thousands separator
f"{0.847:.0%}"                   # "85%" — format as a percentage

f-strings (Python 3.6+) replaced older %-formatting and .format(). Use them by default — they're faster and far more readable. The : inside a {} starts a format spec: .2f (2 decimals), , (grouping), % (percent), >10 (right-align in 10 chars).