Key Takeaways: Python Fundamentals I — Variables, Data Types, and Expressions

This is your quick-reference card for Chapter 3. Keep it open while you work through exercises, and come back to it whenever you need a reminder. These fundamentals will be used in every single chapter that follows.


Core Concepts

  • Variables are labels, not boxes. A variable is a name that points to a value in memory. When you write b = a, both names point to the same value — no copy is made. This distinction becomes critical when you work with lists and dictionaries in Chapter 5.

  • Data types encode meaning. Choosing int vs. str for a value isn't a technical detail — it's a statement about what the data represents. ZIP codes are strings because you'd never add two ZIP codes together. Ages are integers because averaging them is meaningful. Get this wrong and your analysis can be silently corrupted.

  • Strings are immutable. String methods like .upper(), .strip(), and .replace() return a new string. They never modify the original. If you want the result, save it to a variable.

  • Error messages are your friends. Read from the bottom up. The last line tells you the error type and description. The line number tells you where to look. Every programmer gets errors constantly — the skill is reading them, not avoiding them.

  • The type() function is your best debugging tool. When something doesn't work the way you expect, check type() first. Nine times out of ten, the issue is a type mismatch.


Data Types Reference

Type Python Name Example Values Use For
Integer int 42, -7, 0, 2024 Counts, years, indices — discrete quantities
Float float 3.14, -0.5, 0.0, 73.0 Rates, measurements, prices — continuous quantities
String str "hello", 'data', "" Names, labels, IDs, dates, any text
Boolean bool True, False Yes/no conditions, comparisons, flags

Key rule: If you wouldn't do arithmetic with it, store it as a string. ZIP codes, phone numbers, patient IDs, and product codes are strings, not numbers.


Operators Reference

Category Operators Notes
Arithmetic + - * / // % ** / always returns a float; // is floor division; % is remainder; ** is exponent
Comparison == != < > <= >= Return True or False; == is comparison, = is assignment
Logical and or not Combine or invert boolean values
Assignment = += -= *= /= x += 5 is shorthand for x = x + 5

Precedence (highest to lowest): ** then * / // % then + - then comparisons then not then and then or. When in doubt, use parentheses.


String Methods Cheat Sheet

Method What It Does Example Result
.strip() Remove leading/trailing whitespace " hi ".strip() "hi"
.upper() All uppercase "hi".upper() "HI"
.lower() All lowercase "HI".lower() "hi"
.title() Capitalize each word "hello world".title() "Hello World"
.replace(old, new) Replace substring "cat".replace("c","b") "bat"
.split(sep) Split into list "a,b,c".split(",") ["a","b","c"]
.startswith(s) Check prefix "data".startswith("da") True
.endswith(s) Check suffix "file.csv".endswith(".csv") True

Remember: All string methods return a new string. The original is never modified.

f-String Formatting

Format What It Does Example Result
{x} Insert value f"count: {42}" "count: 42"
{x:.2f} 2 decimal places f"{3.14159:.2f}" "3.14"
{x:,} Comma separator f"{1000000:,}" "1,000,000"
{x:<20} Left-align, width 20 f"{'hi':<20}" "hi "

Indexing and Slicing

 D   a   t   a
 0   1   2   3      ← positive indices
-4  -3  -2  -1      ← negative indices
  • s[0] — first character
  • s[-1] — last character
  • s[1:3] — characters at index 1 and 2 (stop index excluded)
  • s[:4] — first four characters
  • s[4:] — everything from index 4 onward

Type Conversion Reference

Function Converts To Common Gotcha
int(x) Integer Truncates floats (3.9 becomes 3); fails on "3.14"
float(x) Float Works on integer strings like "42"
str(x) String Works on anything; result is text, not a number
bool(x) Boolean 0, 0.0, "", None are False; everything else is True
round(x, n) Rounded number Not a type conversion, but often used alongside int()

The two-step conversion: To convert "3.14" to an integer, go through float: int(float("3.14")) gives 3.


Common Errors Reference

Error What Python Is Saying Most Common Cause How to Fix
NameError "I don't know that name" Typo in variable name; variable not defined; cell not run Check spelling; run the defining cell
TypeError "Wrong type for this operation" Adding str + int; indexing a number Use type() to check; convert with int(), str(), etc.
SyntaxError "I can't even parse this code" Missing quote, missing parenthesis, = vs == Check matching quotes and parentheses; check the line above
ValueError "Right type, wrong value" int("hello"), int("3.14") Ensure the value can actually be converted
ZeroDivisionError "Can't divide by zero" Denominator is 0 Check your data; add a zero-check before dividing

What You Should Be Able to Do Now

Use this checklist to verify you've absorbed the chapter. If any item feels uncertain, revisit the relevant section.

  • [ ] Create variables with descriptive snake_case names and assign them values of type int, float, str, or bool
  • [ ] Use type() to check the data type of any value
  • [ ] Evaluate arithmetic expressions and correctly predict the result, including operator precedence and the difference between / and //
  • [ ] Build f-strings that embed variables and format numbers (decimal places, comma separators)
  • [ ] Use string methods (.strip(), .upper(), .lower(), .replace(), .split()) to clean and transform text
  • [ ] Index and slice strings to extract individual characters or substrings
  • [ ] Write comparison expressions using ==, !=, <, >, and combine them with and, or, not
  • [ ] Convert between types using int(), float(), str(), and bool(), and know the common gotchas
  • [ ] Read a Python error message and identify the error type, the line number, and the likely cause
  • [ ] Distinguish between values that look like numbers but should be stored as strings (ZIP codes, IDs) and values that are genuine numeric quantities
  • [ ] Store dataset metadata in well-named Python variables (project milestone)

If you checked every box, you have a solid foundation. In Chapter 4, you'll learn control flow — how to make your programs make decisions and repeat operations — and these fundamentals will be the building blocks for everything that follows.