Menu
CoddyTech

Truth Tests and Fallbacks

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

Use Python truth testing without losing valid zero values.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

string name = "";
int? limit = 0;
Console.WriteLine(name.Length == 0 ? "Guest" : name);
Console.WriteLine(limit ?? 10);

Python

name = ""
limit = 0
print(name or "Guest")
print(10 if limit is None else limit)

What changes

C# ordinary conditions require bool; integers, strings and lists have no general automatic truth conversion. Python allows truth testing: None, False, numeric zero and empty built-in containers are false. Nonempty strings, including "False", are true. Python and/or short-circuit and return an operand, whereas ordinary C# &&/|| operate on booleans. User-defined C# true/false operators are a separate advanced feature, not arbitrary truthiness.

Transfer mistake

Python value or fallback is not C# value ?? fallback: or also replaces zero and empty values. An explicit None test preserves a real zero.

Your task

Read a display name and a limit token. Substitute Guest for an empty name. The scaffold converts the second line from missing or an integer in [0, 20] into None or int. Substitute 10 only for None, preserving zero. Output the selected name and limit on separate lines. Treat these as separate policies: empty-name fallback and nullable-limit fallback.

challenge icon

Challenge

Beginner

Read a display name and a limit token. Substitute Guest for an empty name. The scaffold converts the second line from missing or an integer in [0, 20] into None or int. Substitute 10 only for None, preserving zero. Output the selected name and limit on separate lines. Treat these as separate policies: empty-name fallback and nullable-limit fallback.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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 C# Developers

Practice on your own: Online Python compiler