Getting Data In and Out
A program that cannot communicate is useless. Input brings data in (from the keyboard, a file, a network); output sends results out (to the screen, a file, a device). The simplest pair is reading a line of text from the user and printing a result.
A crucial subtlety: input usually arrives as text (a string), even when it represents a number. Reading "42" from the keyboard gives the string "42", not the integer 42. To do arithmetic you must convert (parse) it: int("42") yields 42. Forgetting this is why "1" + "1" from user input produces "11" rather than 2.
Files are the standard way to store data that outlasts a single run. The usual discipline is: open the file (specifying read or write mode), process it, then close it (releasing the resource and flushing buffered writes). A common and robust mental model is the stream: rather than loading a giant file entirely into memory, a program reads it piece by piece — line by line, for example — which lets it handle files far larger than memory.
| Step | Purpose |
|---|---|
| Open | Connect to the file (read or write mode) |
| Process | Read from or write to it |
| Close | Release the file and flush writes |
Common pitfall: treating input as already numeric. Data read from a user or a file is text;"5" + "3"is"53", not8. Convert the string to a number (int(...)orfloat(...)) before doing arithmetic, and be ready for the conversion to fail if the text is not a valid number.