Menu
CoddyTech

Truth Tests Beyond boolean

Lesson 9 of 48 in Coddy's Python for Java Developers course.

Python conditions can test objects directly. Java if requires boolean or Boolean (unboxed); a list or integer is not a condition. Empty Python containers, empty strings, numeric zero, None, and False test false. Nonempty strings such as "false" test true. Python and/or short-circuit but return an operand rather than necessarily a bool; not always returns a bool. Use name or "Guest" when an empty name should trigger a fallback. Use a None check when zero is meaningful.

Java excerpt: inside main

var names = new java.util.ArrayList<String>();
if (!names.isEmpty()) { System.out.println("present"); }
Integer limit = 0;
System.out.println(limit == null ? 10 : limit);

Python

names = []
if names:
    print("present")
limit = 0
print(10 if limit is None else limit)

Watch the difference

Neither Java nor C# permits arbitrary collection truthiness. Do not infer Python behavior from those languages, and do not use limit or 10 when a valid zero must survive.

Practice

Apply this comparison in the task below. Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Read a display name and a limit token. The name can be empty; the token is missing or an integer 0 through 20, parsed by the scaffold. Print the name, substituting Guest only for empty text. Then print the limit, substituting 10 only for None and preserving zero. Java requires explicit boolean conditions; Python truth tests can express the name fallback, but not a missing-only numeric fallback.

Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler