readLines and Text Contracts
Lesson 27 of 48 in Coddy's Python for R Developers course.
R readLines returns a character vector of lines; Python input reads one line and removes its newline. Python raises EOFError if no line remains. R numeric formatting can switch to scientific notation depending on settings, so exact output tasks need explicit formatting. Python f-strings also allow explicit format specifications. Strip surrounding whitespace without removing spaces inside a product label. Keep integer cents until display and format the remainder to two digits. The locked drivers handle input and output around the editable APIs; extra prompts or diagnostic prints alter stdout and fail the contract.
R
label <- trimws(" Green tea ")
cents <- 305
cat(sprintf("%s: %d.%02d\n", label, cents %/% 100, cents %% 100))Python
label = ' Green tea '.strip()
cents = 305
print(f'{label}: {cents // 100}.{cents % 100:02d}')Porting trap
An R console representation is not the same as plain serialized output. Use deliberate formatting in both languages.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler