Text Input and Exact Output
Lesson 27 of 48 in Coddy's Python for C++ Developers course.
Python input() reads a line without its ending newline and returns str. Unlike formatted C++ stream extraction with >>, it does not parse numbers or stop at internal whitespace. Convert numbers with int and strip surrounding whitespace only when the contract requires it. f-strings interpolate values; :02d pads a decimal integer to two characters. For nonnegative cents, // 100 and % 100 separate whole units and cents without floating-point rounding.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
std::string label = "Green tea";
int cents = 305;
std::cout << label << ": " << cents / 100 << '.' << std::setw(2) << std::setfill('0') << cents % 100 << '\n';Python
label = " Green tea ".strip()
cents = 305
print(f"{label}: {cents // 100}.{cents % 100:02d}")Porting trap
input("Prompt: ") writes a prompt and breaks exact-output grading. Keep labels with spaces intact rather than splitting them into tokens.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler