Python

Python Fundamentals

Variables, Data Types & Type Conversion

A variable is a named reference to a value stored in memory. In Python, you don't declare a type — you just assign:

JrCodex·5 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 1 Time to complete: ~25 minutes


Table of Contents

  1. What is a Variable?
  2. Naming Rules & Conventions
  3. Python's Core Data Types
  4. Checking Types with type()
  5. Type Conversion (Casting)
  6. Dynamic Typing — What It Really Means
  7. Summary & Next Steps

1. What is a Variable?

A variable is a named reference to a value stored in memory. In Python, you don't declare a type — you just assign:

age = 25
name = "Alice"
height = 5.6
is_student = True
Variable Assignment
────────────────────────────────────
  age = 25
   │      │
   │      └── value (object in memory)
   └───────── name (label pointing to that object)
────────────────────────────────────

Python variables are labels, not boxes — age doesn't "contain" 25 so much as it points to an integer object 25 somewhere in memory. This matters later when we discuss mutability (Chapter 6).


2. Naming Rules & Conventions

RuleExample
Must start with a letter or underscore_count, total ✓ — 1total
Can contain letters, digits, underscoresuser_id_2
Case-sensitiveage and Age are different variables
Cannot be a reserved keywordclass, for, if

Convention (PEP 8): use snake_case for variables and functions.

user_name = "Bob"      # ✓ preferred
userName = "Bob"       # ✗ camelCase — not Pythonic
UserName = "Bob"       # ✗ reserved for class names

3. Python's Core Data Types

TypeExampleDescription
int42, -7Whole numbers, arbitrary precision
float3.14, -0.5Decimal numbers
str"hello"Text, immutable sequence of characters
boolTrue, FalseLogical values (subtype of int)
NoneTypeNoneRepresents "no value"
age = 25              # int
price = 19.99         # float
name = "Alice"        # str
is_active = True      # bool
result = None         # NoneType — placeholder for "nothing yet"

Lists, tuples, dictionaries, and sets are also core types — they get their own chapters (6–9) since each has enough depth to warrant one.

A Note on int in Python

Unlike many languages, Python's int has no fixed size — it grows as large as memory allows:

big_number = 2 ** 100
print(big_number)
# 1267650600228229401496703205376

4. Checking Types with type()

age = 25
name = "Alice"
price = 19.99
is_active = True
 
print(type(age))        # <class 'int'>
print(type(name))       # <class 'str'>
print(type(price))      # <class 'float'>
print(type(is_active))  # <class 'bool'>

Use isinstance() when you need a boolean check (common in real code, e.g. validating function inputs):

def describe(value):
    if isinstance(value, int):
        print(f"{value} is an integer")
    elif isinstance(value, str):
        print(f"'{value}' is a string")
 
describe(10)      # 10 is an integer
describe("hi")    # 'hi' is a string

5. Type Conversion (Casting)

Convert between types using int(), float(), str(), and bool().

# str → int / float
age_str = "25"
age_num = int(age_str)          # 25
price = float("19.99")          # 19.99
 
# int / float → str
count = 5
message = "Count: " + str(count)   # "Count: 5"
 
# int → float, float → int (truncates, doesn't round)
x = float(7)      # 7.0
y = int(7.9)      # 7  ← truncated, NOT rounded to 8

Common Pitfall: Invalid Conversions

int("hello")     # ValueError: invalid literal for int() with base 10: 'hello'
int("3.5")       # ValueError — must go through float first
float("3.5")     # 3.5  ✓
int(float("3.5")) # 3    ✓ two-step conversion works

Truthiness and bool()

Every value in Python has an inherent truthiness — useful for if conditions (Chapter 10):

print(bool(0))        # False
print(bool(1))        # True
print(bool(""))       # False — empty string
print(bool("hi"))     # True — non-empty string
print(bool([]))       # False — empty list
print(bool(None))     # False
Falsy valuesEverything else is Truthy
0, 0.0, "", [], {}, (), set(), None, Falsenon-zero numbers, non-empty collections, non-empty strings

6. Dynamic Typing — What It Really Means

Python is dynamically typed: a variable can be reassigned to a different type at any time.

x = 5          # x is an int
x = "five"     # now x is a str — totally legal
x = [1, 2, 3]  # now x is a list

This is different from statically typed languages (Java, C++) where a variable's type is fixed at declaration. Dynamic typing gives flexibility but shifts responsibility to you (or tools like mypy, covered in Module 5) to avoid type-related bugs.

Static typing (Java):        Dynamic typing (Python):
──────────────────────       ─────────────────────────
int x = 5;                   x = 5
x = "five";  // ✗ ERROR      x = "five"   // ✓ allowed

7. Summary & Next Steps

Key Takeaways

  • Variables are labels pointing to objects, created on assignment — no type declaration needed.
  • Python's core scalar types: int, float, str, bool, None.
  • Convert between types with int(), float(), str(), bool() — watch for ValueError on invalid strings.
  • Python is dynamically typed: a variable's type can change across its lifetime.

Concept Check

  1. What's the difference between int(7.9) and round(7.9)?
  2. Why does bool([]) evaluate to False?
  3. What error do you get from int("3.5"), and how do you fix it?

Next Chapter

Chapter 3: Operators


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index