The Zero String Trap
Lesson 9 of 48 in Coddy's Python for PHP Developers course.
PHP treats the string "0" as false; Python treats every nonempty string as true. Empty strings and containers, numeric zero, False, and None are false in Python. PHP || returns a boolean; Python or returns a selected operand. PHP ?? falls back for missing or null data, while Python or also replaces zero and empty values. For an already defined name, use an explicit None test for an absence-only fallback.
PHP 8.3
<?php
$text = '0';
echo $text ?: 'Guest', "\n";
echo 0 ?? 10, "\n";Python
text = "0"
print(text or "Guest")
print(0 or 10)Porting trap
A line read from input remains text until converted. Python bool("0") is true even though bool(0) is false. Distinguish missing data from a legitimate zero limit.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
Challenge
BeginnerRead 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler