Python variables, None and truthiness for Java developers

No types on variables, None instead of null, == that means equals(), and an if that accepts a list. Here is how Python variables really work, explained from the Java side, with the traps that catch every Java developer once.

Left, a Java box labelled int count holding the value 3: the box has a type, so only ints fit. Right, a Python name tag labelled count tied with a string to a value card reading 3, type int. A second tag labelled count points to a card reading five, type str, showing the same name can move to a new value of another type. Below, a strip lists what Python treats as false: False, None, 0, empty string, empty list, empty dict.
Fig. 1 — In Java a variable is a typed box. In Python it's a name tag, and the value carries the type.

In Java, before you can store anything, you say what type it is: int count = 0;. The compiler holds you to it forever. Python skips that step: count = 0. That looks like a small change, but it changes how variables, null checks and if conditions work.

This is part 2 of Python for Java Developers. If you haven’t read the overview, start with the 10 differences that matter.

A variable is a name tag, not a box

String model = "gpt";
int maxTokens = 500;
double temperature = 0.7;
boolean stream = true;
String answer = null;
model = "gpt"
max_tokens = 500
temperature = 0.7
stream = True
answer = None

Think of a Java variable as a box with a type label: an int box only takes ints. A Python variable is a name tag you tie to a value. The value knows its own type. The tag doesn’t care, so you can move it:

x = 5
type(x)        # <class 'int'>
x = "five"     # legal: the tag now points to a str
type(x)        # <class 'str'>

That’s dynamic typing. Legal isn’t the same as wise: in real code, keep one name for one kind of thing. Python 3 also supports optional type hints (count: int = 0) that editors and checkers use, but Python itself doesn’t enforce them at runtime.

Three spelling rules to switch on now:

  • Names are snake_case: max_tokens, not maxTokens. Classes stay CamelCase.
  • True, False and None start with a capital letter. true is just an unknown name.
  • There’s no final. A name in UPPER_CASE (MAX_RETRIES = 3) means “treat this as a constant”, by convention.

The basic types

Python Closest Java What to know
int long, BigInteger No size limit, no overflow
float double 64-bit, same rounding surprises
str String Immutable, like Java
bool boolean True / False
None null A real object, the only value of its type

To check a type in code, use isinstance(x, str), which is Python’s instanceof.

Strings you’ll use every day

f-strings are how Python builds text. Put f before the quote and expressions in braces:

String msg = "User " + user + " has " + count + " open tickets";
// or
String msg = String.format("User %s has %d open tickets", user, count);
msg = f"User {user} has {count} open tickets"
f"{price:.2f}"        # 2 decimal places
f"{count + 1}"        # any expression works

Triple quotes make multi-line strings, like Java’s text blocks. You’ll see them for prompts and SQL:

prompt = f"""You are a helpful support agent.
Answer in two sentences.

Question: {question}"""

The methods you’ll reach for most:

text = "  Hello World  "
text.strip()            # "Hello World"     (Java: strip())
text.lower()            # "  hello world  "
"a,b,c".split(",")      # ["a", "b", "c"]
", ".join(["a", "b"])   # "a, b"   join is called on the separator
len(text)               # 15       len() is a function, not a method
"World" in text         # True     (Java: contains())
text[:5]                # first 5 characters (slicing)

None is Python’s null

None plays the role of null: “no value here”. A function that doesn’t return anything returns None, and dict.get() returns None for a missing key.

Check for it with is:

if answer is None:
    answer = "No answer yet"

And meet the error you’ll see instead of a NullPointerException:

AttributeError: 'NoneType' object has no attribute 'strip'

It means you called a method on None. Look for a function that returned nothing, or a .get() that found no key.

== vs is: the trap that flips your Java habit

This one is backwards from Java, so read it twice:

Question Java Python
Same value? a.equals(b) a == b
Same object? a == b a is b

So in Python, comparing strings with == is correct:

if name == "Asha":       # right: compares the text
    ...

And is checks identity, which is almost never what you want for strings or numbers:

a = 1000
b = int("1000")
a == b      # True:  same value
a is b      # False: two different int objects

Sometimes is happens to return True for small numbers or short strings, because Python reuses some objects. Never rely on it. The rule is simple: use == for values, and is only for None (and True/False in rare cases).

Truthiness: an if accepts anything

In Java, an if needs a boolean. In Python, any value can stand in a condition. These count as false (they’re “falsy”):

  • False and None
  • zero: 0, 0.0
  • empty things: "", [], {}, (), set()

Everything else is true (“truthy”). That gives you the most common line in Python code:

List<Doc> docs = search(query);
if (docs == null || docs.isEmpty()) {
    System.out.println("Nothing found");
}
docs = search(query)
if not docs:
    print("Nothing found")

if not docs: means “if docs is empty or None”. One check covers both.

The logic words are plain English: and, or, not instead of &&, ||, !. And they return one of their operands, not just True or False, which gives you a handy default-value idiom:

name = user_name or "guest"     # "guest" if user_name is None or ""

Numbers without surprises (mostly)

7 / 2       # 3.5     / always gives a float
7 // 2      # 3       // is whole-number division (Java's int / int)
7 % 2       # 1       remainder, as in Java
2 ** 10     # 1024    power (Java: Math.pow)
10 ** 30    # a 31-digit int, no overflow

There’s no ++ or --. Write count += 1. And comparisons can chain like in maths: 0 <= temperature <= 1.

Assigning more than one name

Python can assign several names in one line, and swap them without a temp variable:

x, y = 3, 4
x, y = y, x          # swap
first, *rest = [1, 2, 3, 4]    # first = 1, rest = [2, 3, 4]

This is called unpacking. It’s also how a function “returns two values”, which you’ll see in a later part.

Key takeaways

  • A Python variable is a name tag; the value carries the type. Check it with type() or isinstance().
  • Use snake_case, capitalised True/False/None, and UPPER_CASE for constants by convention.
  • None is Python’s null; AttributeError: 'NoneType'... is Python’s NullPointerException.
  • == compares values (Java’s equals). Use is only for None.
  • Empty things, zero and None are falsy, so if not items: checks for empty or missing.
  • / gives a float, // gives an int, and there is no ++.

Frequently asked questions

What is the Python equivalent of null?

None. It’s a real object, the only value of type NoneType. Check for it with x is None, not x == None.

What is the difference between is and == in Python?

== checks whether two values are equal, like Java’s equals(). is checks whether two names point to the exact same object, like Java’s == on references. Use == for comparisons and is only for None.

What are truthy and falsy values in Python?

Falsy values are treated as false in a condition: False, None, 0, 0.0, and empty strings, lists, dicts, tuples and sets. Everything else is truthy.

Does Python have constants?

Not enforced ones. By convention, a name in UPPER_CASE at the top of a module is a constant, and other developers won’t reassign it. Type checkers can enforce it with typing.Final.

How do I check the type of a variable in Python?

Use type(x) to see it, and isinstance(x, int) to test it in code. isinstance also accepts subclasses, just like Java’s instanceof.

Next in the series: Python for loops: range, enumerate and zip, and why there’s no for (int i = 0; ...) in Python.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.