Python Nullable Types (Type?) & Non-Nullable Invariants
When a value can legitimately be absent (e.g. an optional middle name, a pending API request, a missing cache entry), suffixing the type with a question mark (`Type?`) opts that variable into nullability. The compiler treats `Type` and `Type?` as separate distinct types, preventing unsafe operations until unwrapped.
"`Type` is a physical coffee mug that always contains liquid; `Type?` is an opaque sealed delivery box that might contain a coffee mug or might be empty."
Deep Dive: How It Works
Subtype Relationship: `Type` is a subtype of `Type?`. You can always assign non-nullable `String` to `String?`, but not vice versa.
Compile-Time Interception: Calling `.toUpperCase()` on `String?` fails compilation until safely guarded or unwrapped.
`Null` Type: The value `null` has the static type `Null`, which is a subtype of all nullable types `T?`.
Syntax Blueprint
String? nickname;
// print(nickname.length); // COMPILE ERROR!
if (nickname != null) {
print(nickname.length); // Safe! Smartly promoted to String
}Nullable type declaration and safe flow analysis unwrap.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to pass a `String?` directly into a function expecting `String`.Why it happens: Nullable types are wider than non-nullable types.
How to fix: Provide a fallback with null-coalescing: `func(param ?? "default")`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Safe Nullable Greeting
Write function `String greet(String? name) { if (name != null) return "Hello $name"; return "Hello Guest"; }`.
In `main()`, print `greet("Alice")` and `greet(null)`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.