gets, input, and Formatting
Lesson 27 of 48 in Coddy's Python for Ruby Developers course.
Ruby gets reads a line including its newline and returns nil at end of input. Python input removes the trailing newline and raises EOFError when no line is available. Neither automatically parses numbers. Ruby strip and Python strip remove surrounding whitespace; splitting with no explicit separator groups whitespace into fields. Keep internal spaces in labels when the contract permits them. For currency display, format integer cents with a whole-number part and a two-digit remainder. A locked driver owns prompts and output in these exercises, so adding debug labels changes the required stdout and fails exact comparisons.
Ruby
label = ' Green tea '.strip
cents = 305
puts "#{label}: #{cents / 100}.#{format('%02d', cents % 100)}"Python
label = ' Green tea '.strip()
cents = 305
print(f'{label}: {cents // 100}.{cents % 100:02d}')Porting trap
Ruby String to_i tolerates malformed prefixes; Python int does not. The valid input contract or a specific exception handler must account for that difference.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler