Study Guide: Variables & Data Types

Module 2 • Introduction to Python

1. Variables and Assignment

Key Concept: A variable is a name that refers to a value stored in memory. You create variables using the assignment operator =, which works from right to left.

How Assignment Works

Python evaluates the expression on the right side of = first, then stores the result in the variable on the left.

x = 10          # Store 10 in x
y = x + 5       # Evaluate x + 5 (15), store in y
x = x + 1       # Evaluate x + 1 (11), store back in x

Naming Rules

Common Mistake: Confusing = (assignment) with == (comparison). In Python, x = 5 means "assign 5 to x." The expression x == 5 means "is x equal to 5?" and returns a Boolean.

2. Numbers: Integers and Floats

Key Concept: Python has two main numeric types. Integers (int) are whole numbers. Floats (float) have decimal points.

The Seven Arithmetic Operators

Know each operator and what it returns:

Remember: Division (/) always returns a float, even for 10 / 2 = 5.0. Use // if you want an integer result.

Order of Operations (PEMDAS)

  1. Parentheses ()
  2. Exponents **
  3. Multiplication, Division, Int Division, Modulo (left to right)
  4. Addition, Subtraction (left to right)

Integer Division and Modulo Pattern

# Convert total minutes to hours and minutes
total_minutes = 135
hours = total_minutes // 60     # 2
minutes = total_minutes % 60    # 15

# Check if a number is even
number % 2 == 0   # True if even

3. Strings

Key Concept: Strings are sequences of characters enclosed in quotes. Single quotes and double quotes work identically.

Essential String Operations

Escape Characters to Know

Common Mistake: Trying to concatenate a string and a number directly. "Age: " + 25 causes a TypeError. Fix it with "Age: " + str(25).

4. Booleans and Type Conversion

Key Concept: Booleans have exactly two values: True and False (capitalized). Every value in Python is either "truthy" or "falsy."

Type Conversion Functions

Falsy Values (everything else is truthy)

Tricky case: bool("0") is True because "0" is a non-empty string. The character "0" is still content. Only "" is falsy.

5. Review Questions

Q1: What value does x hold after: x = 10; x += 5; x *= 2?

A: 30 (10 + 5 = 15, then 15 * 2 = 30)

Q2: What is 17 // 3 and 17 % 3?

A: 5 and 2 (17 = 5*3 + 2)

Q3: What does type(10 / 5) return?

A: <class 'float'> -- division always returns a float (even 10/5 = 2.0)

Q4: How do you convert "3.14" to an integer?

A: int(float("3.14")) -- convert to float first, then to int. Direct int("3.14") causes a ValueError.

Q5: Which of these are falsy: 0, "hello", "", None, "False", -1?

A: 0, "", and None are falsy. "hello", "False" (non-empty string!), and -1 (non-zero number) are truthy.

Q6: What is len("Hi\nBye")?

A: 6 -- \n counts as one character: H-i-\n-B-y-e = 6

6. Key Terms Summary