Lesson · Getting Started
Basic Console Input & Output
57 min readBasic Console Input & Output
Console input and output are the simplest way to make a program interactive. This lesson also introduces the important idea that external input arrives as text and must be validated or converted.
Learning goals
- Call
input()with a prompt and explain exactly what it returns for every user action, including pressing Enter with no text. - Convert console text with
int()orfloat()at the boundary and reprompt from theValueErrorinstead of crashing. - Use
print()'ssepandendkeywords to control spacing and line endings in multi-part output. - Split one input line into fields with
split()and convert each field before using it. - Build the prompt, parse, validate, respond loop that interactive programs repeat.
Mental model
The arrow worth remembering is the second one: the value from input is never a number until you convert it, so every numeric bug in an interactive program starts by skipping that step.
Mental model
read it top to bottom
input("Age: ") writes the prompt, reads one line
↓ returns str always text, even for digits
int(...) / float(...) converts, or raises ValueError
↓ converted value
print(...) formats the result for the userCore idea
Interactive programs have one narrow doorway called the boundary: everything users type arrives as a str, and the program's job is to convert and validate at that doorway before the value travels inward. Keep parsing close to input and formatting close to print, and the middle of the program only sees trustworthy types.
input()
input(prompt) writes the prompt without adding a newline, reads one line from the user, strips the trailing newline, and returns the rest as a str. Pressing Enter returns an empty string, and end-of-input raises EOFError.
input() returns text
input() always returns a str after removing the trailing newline. Numeric or structured input therefore needs explicit parsing and validation.
Converting input with int(), float() and other constructors
Convert console text at the program boundary using constructors such as int() or float(). Handle conversion failure where you can ask again or report a useful input error.
Prompts
A prompt is the string passed to input() and shown to the user before reading. Keep it short and end it with ": " so the user's typing appears on the same line instead of under it.
Reading multiple values with split()
split() separates one input string into fields, commonly on whitespace. The result is still a sequence of strings until each field is converted.
print() arguments
print() accepts multiple objects, converts them to text, and separates them with sep. end, file, and flush control termination, destination, and buffering behavior.
sep
sep is the print() keyword that sets the text placed between arguments; its default is a single space. Passing sep="" joins the arguments with nothing, and sep=", " produces a comma-separated line.
end
end is the print() keyword appended after the last argument; its default is "\n", which starts a new line. end="" keeps the next print on the same line, which is how progress dots and prompts without a trailing newline are built.
Basic formatted output
Use f-strings to place values inside readable output and apply width or numeric formatting. Keep presentation formatting separate from the underlying numeric data model.
Basic input validation
Basic input validation should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
Interactive program loop preview
Interactive programs often repeat prompt → parse → validate → respond. A loop makes retry behavior explicit and provides a natural place for exit commands or end-of-input handling.
Walkthrough
input("Name: ")writes the prompt, reads one line, and returns it asstrwithout the trailing newline;.strip()removes surrounding whitespace so" Ada "becomes"Ada".- The
while Trueloop retries untilbreak.raw_age = input(...)keeps the text exactly as typed, and the separate name makes the unparsed value available if the conversion fails. int(raw_age)raisesValueErrorfor anything that is not an integer, theexceptblock prints a hint and loops again, andbreakruns only after a successful conversion, soageis bound before the loop exits.- Predict before running: what
agecontains after the input" 12 ", whyraw_ageis kept as a separate name, and what happens after three failed attempts.
Experiments to try
- Enter
12.5for the age and read theValueErrorpath; then change the program to accept decimals withfloat()and adjust the message. - Try the answers
+7,7,1_0, and7.0in turn and record which stringsint()accepts and which raiseValueError. - Remove
.strip()and answer with"Ada "; note the difference, then decide which prompts need stripping and why. - Rewrite the final print to read
Ada (12 years)and build the same text once with an f-string and once with+concatenation; explain theTypeErrorthe concatenation version raises ifstr(age)is forgotten.
Common mistakes
- Using the result of
input()as a number without converting: comparisons such asage > 18raiseTypeErrorwhenageis still a string, becausestrandintdo not compare. - Catching
ValueErrorand continuing without rebinding: if the conversion fails, the variable that was supposed to hold the number is unbound, so later use raisesNameError. - Forgetting that
input()returns""when the user presses Enter:int("")raisesValueError, and a blank name formats into an empty slot in the output. - Reading several values with one
inputcall: the line3 4stays a single string untilsplit()turns it into["3", "4"], and each field still needs its own conversion.
Practice: Easy
- Run the worked example and answer
abconce, then12; record the two different paths through the loop exactly as printed. - Print
repr(input("Type: "))for three answers:hello, an empty line, andspaced. Explain whatreprshows that the raw echo would hide. - Change the final print to
print(name, age)and then back to the f-string version. State one advantage of the f-string form.
Practice: Medium
- Read two numbers from one line with
values = input("Two numbers: ").split()and convert both withint. Then supply three values and explain theValueErrorthe unpacking raises. - Reject an empty answer before attempting
int():if not raw_age: print("A number is required."); continue. Explain why this produces a clearer message than the conversion error. - Build a two-column print with an f-string such as
f"{name:<10}{age:>5}"and test it with names of different lengths; check the alignment in both columns.
Practice: Hard
- Write a quiz program that asks three questions and keeps the answers in a list, reprompting after each invalid integer. Decide what counts as invalid for a text answer and document the rule in a comment.
- Extend the loop so that
quit, typed in any case, exits instead of reprompting forever. Explain which value you test and where the check belongs relative to the conversion. - Write "read two integers and print their sum" twice: once with two
inputcalls and once with one call plussplit(). State which version handles redirected input from a file better and what assumption each makes.
Lesson checklist
- I can explain exactly what
input()returns and what arrives when the user presses Enter with no text. - I can convert a console string to
intorfloatand reprompt from theValueErrorpath. - I can control output spacing and line endings with
sep,end, and f-string formatting. - I can split one input line into fields and convert each field before using it.
Remember
Console I/O has one boundary: text comes in and typed values go out. `input()` always hands you a `str`, so convert with `int` or `float` right at the prompt and let `ValueError` drive the retry loop; f-strings and `print`'s options handle everything the user sees.
Interview angles
What is the main purpose of **input()**?+
input(prompt) writes the prompt without adding a newline, reads one line from the user, removes the trailing newline, and returns the rest as a str. Pressing Enter returns an empty string, and end-of-input raises EOFError.
What should you pay attention to when using **input() returns text**?+
input() always returns a str after removing the trailing newline. Numeric or structured input therefore needs explicit parsing and validation.
How does **Converting input with int(), float() and other constructors** fit into this lesson?+
Convert console text at the program boundary using constructors such as int() or float(). Handle conversion failure where you can ask again or report a useful input error.
Why does the retry loop keep `raw_age` (the string) as a separate name from `age` (the number)?+
After a failed int(), age has no value for that attempt, so the loop needs the original text to show an error or reprompt. Separating what the user typed from the parsed value makes the retry path explicit.