Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
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