Variables & Types
Static typing vs dynamic typing
Introduction
In this lesson, you'll learn about variables & types in Python. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with static typing vs dynamic typing.
Python has its own approach to static typing vs dynamic typing, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
name = "Alice"
age = 30
score = 9.5
active = True
MAX = 100 # UPPER_CASE = constant by convention
# Optional type hints
city: str = "Istanbul"
# Types can change (though not recommended)
x = 42
x = "now a string" # valid in PythonComparing to Java
Here's how you might have written similar code in Java:
String name = "Alice";
int age = 30;
double score = 9.5;
boolean active = true;
final int MAX = 100;
// var (Java 10+)
var city = "Istanbul"; // still String
// Cannot change type
int x = 42;
// x = "string"; // compile errorYou may be used to different syntax or behavior.
Python infers types dynamically; Java requires explicit type declarations
You may be used to different syntax or behavior.
Java final = Python's UPPER_CASE constant convention
You may be used to different syntax or behavior.
Python variables can change type; Java types are fixed
You may be used to different syntax or behavior.
Python type hints are optional documentation; Java types are mandatory
Step-by-Step Breakdown
1. No Type Declarations
Python doesn't need type declarations. Just assign a value — the interpreter figures out the type at runtime.
String name = "Alice"; int age = 30;name = "Alice"
age = 302. Type Hints
Python type hints (PEP 484) are optional annotations for documentation and static analysis tools, not enforced at runtime.
# Without hints
name = "Alice"
# With hints (mypy/pyright can check these)
name: str = "Alice"3. Constants by Convention
Python has no final keyword. Constants are just UPPER_CASE variables — the convention signals 'don't change this'.
final int MAX_SIZE = 100;MAX_SIZE = 100 # convention onlyCommon Mistakes
When coming from Java, developers often make these mistakes:
- Python infers types dynamically; Java requires explicit type declarations
- Java final = Python's UPPER_CASE constant convention
- Python variables can change type; Java types are fixed
Key Takeaways
- No type declarations in Python
- Java final → UPPER_CASE convention in Python
- Types are dynamic in Python; static in Java
- Type hints are optional in Python