Truth Tests and Operands
Lesson 9 of 48 in Coddy's Python for C++ Developers course.
C++ built-in || yields bool after contextual conversions; Python or returns one of its operands. Python empty containers and strings, zero, False, and None test false. A C++ vector cannot be used directly as a condition; test empty(). In Python, if names tests emptiness directly. A nonempty Python string such as "false" tests true. Both languages short-circuit their ordinary logical operators.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
std::vector<int> names;
if (!names.empty()) std::cout << "present\n";
int limit = 0;
std::cout << (limit || 10) << '\n';Python
names = []
if names:
print("present")
limit = 0
print(10 if limit is None else limit)Porting trap
Python limit or 10 replaces a legitimate zero. Use 10 if limit is None else limit when only absence should select the fallback.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler