CLI Input and Exact Output
Lesson 27 of 48 in Coddy's Python for PHP Developers course.
PHP CLI code often reads with fgets(STDIN), which retains the line ending; Python input() removes its trailing newline and returns text. Neither converts numeric input automatically. Python strip() removes surrounding whitespace but preserves internal spaces. Use an f-string with a precision specifier for fixed decimal output, comparable to PHP printf. Prompts and debugging text are part of stdout and will break an exact-output contract.
PHP 8.3
<?php
$label = trim(' Green tea ');
$cents = 305;
printf("%s: %.2f\n", $label, $cents / 100);Python
label = " Green tea ".strip()
cents = 305
print(f"{label}: {cents / 100:.2f}")Porting trap
A PHP web application's request variables and HTML response are not the same interface as these command-line tasks. The locked driver owns standard input/output; implement only the API requested by each task.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
Challenge
BeginnerRead a product label on the first line and a nonnegative integer number of cents on the second. Remove surrounding whitespace from the label but preserve internal spaces. Print exactly label: dollars.cents, with two digits after the decimal point and a final newline. The label may be empty, in which case the output begins with : . Do not print a currency symbol or input 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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler