Chapter 8 of 11
Talking to the Outside World: Input, Output, and Files
Transform your scripts from silent number crunchers into interactive tools that ask questions, display results clearly, and even remember information between runs by saving it to files.
Talking to the Outside World: Big Picture
From Silent Scripts to Interactive Tools
So far your programs mostly worked inside Python. Now we will let them interact with the outside world: asking questions, showing results, and saving data to files.
Three New Superpowers
You will learn three main skills: 1) Input with `input()` to ask the user for data, 2) Output with `print()` and f-strings, and 3) Files with `open()` and `with` to remember data between runs.
What You Will Build
By the end, you will read user input, format friendly messages, and create a small script that reads from a text file, processes the data, and writes results to another file.
Step 1: Getting User Input with input()
Meet input()
`input()` asks the user a question and waits. Example: `name = input("What is your name? ")` then `print("Hello,", name)` greets the user using what they typed.
Input Is Always Text
`input()` always returns a string (text), even if the user types numbers. To use it as a number, you must convert it with `int()` or `float()`.
Converting to Numbers
Example: `agetext = input("How old are you? ")` then `age = int(agetext)` lets you do math like `age + 1`. For decimals, use `float()` instead.
Try It: Simple Input Conversion (No Code Runner Needed)
Imagine this code:
```python
price_text = input("Item price: ")
quantity_text = input("How many? ")
price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print("Total:", total)
```
- If the user types `2.50` for the price and `3` for the quantity, what will `total` be?
- What happens if you forget to convert `pricetext` and write `total = pricetext * quantity`?
Think it through:
- Remember: `input()` returns strings.
- Multiplying a string by an integer repeats the string.
Answer in your head or on paper, then check:
- `total` will be `7.5`.
- `"2.50" * 3` becomes `"2.502.502.50"`, not `7.5`. This is why conversion matters.
Step 2: Clear Output with print() and f-strings
Basic print()
`print()` shows information on the screen. Example: `print("Player:", name, "Score:", score)` prints several pieces separated by spaces.
What Is an f-string?
An f-string starts with `f` and lets you put variables inside `{}`. Example: `print(f"Player: {name} | Score: {score}")` is shorter and clearer.
Formatting Numbers
You can control number format: `total = 7.5` then `print(f"Total: ${total:.2f}")` prints `Total: $7.50`. The `.2f` means 2 decimal places.
Quick Check: Output Formatting
Choose the best way to print a neat message using a name and a score.
You have `name = "Sam"` and `score = 18`. Which line prints: `Sam scored 18 points` in the clearest, most modern style?
- print("Sam scored", score, "points")
- print("name scored score points")
- print(f"{name} scored {score} points")
- print("{} scored {} points".format(name, score))
Show Answer
Answer: C) print(f"{name} scored {score} points")
Option 3 uses an f-string, which is the clearest modern style. Option 1 works but hardcodes the name. Option 2 prints the words 'name' and 'score'. Option 4 works but is less beginner-friendly than f-strings.
Step 3: Reading and Writing Text Files Safely
Why Use Files?
Files let your program remember data between runs, like scores or settings. We usually use plain text files such as `.txt` or `.csv`.
Using with open(...)
Use `with open("scores.txt", "r", encoding="utf-8") as f:` then `data = f.read()`. The `with` block auto-closes the file when finished.
Write vs Append Modes
`"w"` write mode creates or overwrites a file. `"a"` append mode adds new text to the end. Always include `encoding="utf-8"` for reliable text handling.
Step 4: Reading a File Line by Line and Processing Numbers
Here is a complete example that reads numbers from a file, one per line, and calculates their total and average.
Thought Exercise: Fix the Buggy File Script
Here is a script with two common mistakes when working with files and numbers:
```python
with open("ages.txt", "r") as f:
data = f.read()
ages = data.split("\n")
total = 0
for age in ages:
total = total + age
average = total / len(ages)
print(f"Average age: {average}")
```
Questions:
- What type is each `age` in the loop? Text or number?
- What error will you get when you run this code?
- How would you fix it so it correctly calculates the average age?
Hints:
- You need to convert each `age` to an `int` or `float`.
- You should ignore empty lines.
A fixed version might:
- Strip each line.
- Check it is not empty.
- Convert to `int` before adding to `total`.
Quick Check: File Modes and Encodings
Test your understanding of how to open files safely.
Which line is the **best** modern way (as of 2026) to open a text file for writing, making sure it uses UTF-8 and closes correctly?
- f = open("data.txt", "w")
- with open("data.txt", "w", encoding="utf-8") as f:
- with open("data.txt", "r", encoding="utf-8") as f:
- open("data.txt", "w", encoding="ascii")
Show Answer
Answer: B) with open("data.txt", "w", encoding="utf-8") as f:
Option 2 uses a `with` block (auto-close), write mode `"w"`, and `encoding="utf-8"`, which is the standard text encoding today. Option 1 has no encoding and no auto-close. Option 3 is read mode. Option 4 uses ASCII, which cannot handle many common characters.
Step 5: Putting It Together – A Tiny Grade Reporter
Project Goal
We will build a tiny grade reporter: ask for a student's name and three scores, compute the average, show it, and save it to a file.
Inputs and Processing
The script uses `input()` in a `for` loop to collect three scores, converts them with `float()`, and computes an average with `sum(scores) / len(scores)`.
Output and Saving
It prints a clear report using f-strings and appends a line like `Alex: 87.3` to `grades.txt` using `with open("grades.txt", "a", encoding="utf-8")`.
Review: Key Ideas and Terms
Flip through these cards to review the main concepts from this module.
- input()
- A function that pauses the program, shows a prompt, and returns what the user types as a string. You usually convert it to int or float for numbers.
- print()
- A function that sends information to the screen. Often used with f-strings to mix text and variable values in a clear way.
- f-string
- A string that starts with f and allows `{}` placeholders for expressions, for example: `f"Total: {total:.2f}"`.
- with open(...) as f:
- The safest pattern for working with files. It opens a file, gives you a file object `f`, and automatically closes the file when the block ends.
- File modes: "r", "w", "a"
- "r" = read, "w" = write (create/overwrite), "a" = append (add to the end). Used as the second argument to `open()`.
- encoding="utf-8"
- Tells Python to read or write text using UTF-8, the standard encoding on modern systems. Helps avoid weird character errors.
- read() vs line by line
- `f.read()` returns the whole file as one string. Looping `for line in f:` lets you process the file one line at a time, which is better for large files.
Key Terms
- open()
- Python function used to open a file and return a file object for reading or writing.
- read()
- File method that reads the entire contents of a file into a single string.
- input()
- Python function that reads a line of text from the user and returns it as a string.
- print()
- Python function that displays text or values on the screen.
- encoding
- A rule for turning characters into bytes and back. UTF-8 is the most common text encoding used today.
- f-string
- A formatted string literal starting with f that lets you embed expressions inside curly braces, such as f"Name: {name}".
- file mode
- A string like "r", "w", or "a" passed to open() that tells Python whether to read, write, or append.
- text file
- A file that stores data as readable characters, such as .txt or .csv, not as binary formats like images.
- with statement
- Python feature that manages resources like files. `with open(...) as f:` ensures the file is closed automatically.
- line by line iteration
- Looping over a file object with `for line in f:` to process one line at a time, useful for large files.