Menu
CoddyTech

Null, None, and Missing Keys

Lesson 7 of 48 in Coddy's Python for PHP Developers course.

Python spells absence None and booleans True and False. Test absence with is None. PHP isset returns false for both a missing key and a key holding null; array_key_exists can distinguish them. In Python, use key in data for key presence and then inspect its value. Python printing displays boolean words rather than PHP echo's usual boolean-to-string conversion.

PHP 8.3

<?php
$data = ['seats' => null];
echo isset($data['seats']) ? 'yes' : 'no', "\n";
echo array_key_exists('seats', $data) ? 'yes' : 'no', "\n";

Python

data = {"seats": None}
print(data["seats"] is None)
print("seats" in data)

Porting trap

Zero is valid data, not necessarily absence. not value matches zero as well as None; it cannot implement an absence-only test.

Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.

challenge icon

Challenge

Beginner

Read an integer seat count from 0 to 20. Print whether any seats remain, using Python's boolean spelling. On the next line print the count if it is positive, or None if it is zero. Initialize the reported value to None and replace it when seats remain.

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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for PHP Developers

Practice on your own: Online Python compiler