Standard Input & Output in Python
I/O operations are the most basic way for a program to communicate with the user. Python processes these through the standard output (
stdout) and standard input (stdin) streams.Output with print()
The
print() function sends text or data to the console.python
Custom sep and end
By default,
print() separates arguments with a space and ends with a newline (\n). You can change this behavior:python
Input with input()
The
input() function pauses your program and waits for the user to type something. Wait! The value returned is always a string.python
Warning: Usetry/exceptfor safety when casting user input to a number!
Formatting with F-Strings (Python 3.6+)
F-strings (formatted string literals) are the modern and preferred way to format strings. They're fast, readable, and allow you to embed Python expressions directly into strings.
python
Older Formatting Methods
While f-strings are the standard, you might see these in older codebases:
1. str.format() Method
python
2. % Operator (Legacy)
Commonly used in Python 2, this is similar to C's
printf.python
Complex Output: Pretty Print
For nested dictionaries or large lists, use the built-in
pprint module for readable console output.python
Direct File I/O: You can also useprint()to write directly to a file:python
Summary
| Feature | Usage | Purpose |
|---|---|---|
| print() | print(val) | Show data |
| input() | input("?") | Get user data |
| f-strings | f"{val}" | Modern formatting |
| .format() | "{0}".format(v) | Older formatting |
| pprint | pprint(data) | Human-readable output |