Input & Output
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.
Two mail slots
step 1 / 5The program printed a prompt and is now frozen at input() โ nothing happens until the world posts something through the IN slot.
The I/O toolbox
| channel | read | write | notes |
|---|---|---|---|
| console | input(prompt) โ str | print(*args, sep=" ", end="\n") | input ALWAYS returns str; print coerces via str() |
| files | open(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 line | sys.argv (list of str) | โ | argv[0] is the script name |
| environment | os.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}.")n = input("number? ") and the user types 5. What is n?
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."