Truth Tests and Operands
Lesson 9 of 48 in Coddy's Python for C Developers course.
C treats a non-null pointer as true even when it points at an empty string. Python tests the string contents: an empty string is false, as are empty containers, zero, None, and False. A nonempty string such as "false" is true. C logical operators produce int 0 or 1; Python and/or short-circuit and return a selected operand. Use name or "Guest" when empty text means missing display text. For a limit where zero is valid, use an explicit None check instead.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
const char *text = ""; int left = 0, right = 9;
printf("%d %d\n", text != NULL, left || right);
return 0;
}Python: complete example.py
print(bool(""), 0 or 9)Watch the difference
Python and/or are not bitwise &/|, and their return value need not be bool. A nonempty list containing zero is true because list truthiness depends on length.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerRead 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.
Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.
An empty Python string is false, unlike a non-null C pointer to an empty string. Preserve a valid numeric zero.
Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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 Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler