Menu
CoddyTech

Truthiness and Short-Circuit

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

Separate a false value from a missing value when applying defaults.

JavaScript

console.log(Boolean([]));
console.log("" || "backup");
console.log(0 || 9);

Python

print(bool([]))
print("" or "backup")
print(0 or 9)

What changes

The empty-list result differs: JavaScript prints true, while Python prints False. Both programs then print backup and 9. Python treats None, numeric zero, empty strings, and empty collections as false. Nonempty strings are true even when the text is "0" or "False". bool(value) exposes that truth value. Python or returns its first operand when that operand is truthy; otherwise it evaluates and returns the second. and returns its first operand when that operand is falsy; otherwise it returns the second. They return operands, not necessarily booleans. not always returns a boolean. The unneeded right operand is not evaluated.

Common mistake

Python empty lists and dictionaries are false, unlike JavaScript arrays and objects. Also, limit or 10 replaces a valid zero with ten. Use a specific absence check when zero has meaning; an or fallback intentionally groups every falsy value together.

Your task

Use the broader fallback rule for an empty name, but the narrower missing-only rule for the numeric limit. Preserve a space-only name because it is nonempty.

challenge icon

Challenge

Beginner

Read a display name and a limit token on two lines. The name may be empty; use Guest only for an empty name. The limit token is missing or an integer from 0 to 20. The scaffold parses it. Use a default limit of 10 only for None, preserving a real zero. Print the selected name and selected integer limit on separate lines.

Print only these lines, ending each with a newline. Keep the supplied input scaffold; it reads the stated values without prompts.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

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 JavaScript Developers

Practice on your own: Online Python compiler