A conversation through two mail slots

Input & Output

The analogy

A program is a sealed room with two mail slots. Through the IN slot the outside world posts values โ€” a typed answer, a file, a click. Through the OUT slot the program posts its replies โ€” text on a screen, a saved file, a sound. Everything a program ever does for anybody passes through these two slots. The catch: whatever comes through the IN slot arrives as plain text, even if the human meant a number โ€” which is why input and casting are best friends. A program with no OUT slot might compute the meaning of life; nobody will ever know.

Visualizer

Two mail slots

step 1 / 5
THE PROGRAM โ€” a sealed room, two slots
IN slot: (waiting...)
OUT slot: (nothing yet)

The program printed a prompt and is now frozen at input() โ€” nothing happens until the world posts something through the IN slot.

๐Ÿ“– In depth โ€” the full reference

The I/O toolbox

channelreadwritenotes
consoleinput(prompt) โ†’ strprint(*args, sep=" ", end="\n")input ALWAYS returns str; print coerces via str()
filesopen(p).read() / .readlines()open(p, "w").write(s)use `with open(...) as f:` โ€” closes even on error
formatted outputโ€”f"{name}: {price:.2f}"f-strings: {value:format}; .2f = 2 decimals, >8 = right-align in 8
command linesys.argv (list of str)โ€”argv[0] is the script name
environmentos.environ.get("KEY")โ€”how servers receive secrets

The rules

  • input() strips the trailing newline but nothing else โ€” .strip() user input before validating.
  • print(a, b) inserts a space and adds a newline; print(x, end="") suppresses the newline for progress bars.
  • I/O is ~1000ร— slower than arithmetic: read once into memory, compute, write once โ€” never print inside a hot loop you care about.
  • Files are bytes until decoded: open(p, encoding="utf-8") explicitly, or Windows will one day choose cp1252 for you.
  • Keep compute functions print-free โ€” return values and test them; print only at the edges.
name = input("Name? ")      # IN slot (always a string)
age = int(input("Age? "))   # IN + cast

print(f"Hi {name}!")        # OUT slot
print(f"Next year you will be {age + 1}.")
Check yourself

n = input("number? ") and the user types 5. What is n?

Practice โ€” write it yourself

greet(name, age) returns the exact string: Hi NAME! Next year you will be AGE+1. โ€” e.g. greet("Ada", 12) -> "Hi Ada! Next year you will be 13."

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser