Python: Input and Output
Learn every way Python sends data to the screen and reads data from the user, from basic print() to polished f-string formatting.
The print() Function
print() is the most commonly used built-in function in Python. It writes its arguments to standard output (your terminal) followed by a newline. You can pass it any number of values separated by commas, and it will display them all on one line with a space between each by default.
print() Signature
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- *objects: one or more comma-separated values to display
- sep: what goes between values (default is a single space ' ')
- end: what goes at the very end (default is newline '\n')
- file: where to write, defaults to the terminal (sys.stdout)
- flush: whether to force-flush the output buffer immediately
print() Basics
PythonPrinting single values, multiple values, and different data types.
The input() Function
input() pauses the program and waits for the user to type something and press Enter. It optionally accepts a prompt string that is displayed before the cursor so the user knows what to type. A critical point that catches almost every beginner: input() always returns a string, regardless of what the user types. If you need a number, you must convert it explicitly.
input() Always Returns str
Forgetting to convert input to int or float is one of the most common Python beginner mistakes.
- input() without an argument shows no prompt, just waits
- input("Your name: ") shows "Your name: " then waits
- The return value is always str, even if the user types 42
- To get an integer: age = int(input("Enter age: "))
- To get a float: price = float(input("Enter price: "))
- If the user types text when int() is expected, a ValueError is raised
input() Function
PythonTry typing your name and age when the program asks.
print() with sep and end Parameters
The sep parameter controls what character or string is placed between each value you pass to print. The end parameter controls what is placed after the last value. Changing these two parameters gives you fine control over exactly how your output looks without building a formatted string first.
sep and end Use Cases
These two parameters cover most output formatting needs without any string concatenation.
- sep="," to produce CSV-style output: 1,2,3
- sep="\n" to print each value on its own line
- sep="" to concatenate with no separator
- end="" to keep the cursor on the same line (useful inside loops)
- end="\n\n" to add an extra blank line after each print()
Controlling sep and end
PythonChanging separators and line endings without string formatting.
String Formatting with % Style
The % formatting style is the oldest way to embed values inside strings in Python, borrowed directly from C's printf. You write a template string with %s, %d, or %f as placeholders, then follow the string with a % operator and a tuple of values. While you will still encounter this style in older codebases, f-strings are preferred for new code.
% Format Specifiers
Each specifier controls both the type and the display format of the inserted value.
- %s: insert as string (works with any type)
- %d: insert as integer
- %f: insert as float (default 6 decimal places)
- %e: scientific notation
- %.2f: float with exactly 2 decimal places
- %10d: integer padded to width 10 (right-aligned)
- %-10s: string padded to width 10 (left-aligned)
% Style Formatting
PythonThe original Python string formatting, still found in older code.
str.format() Method
The str.format() method was introduced in Python 2.6 as a cleaner replacement for % formatting. You place curly brace placeholders {} inside a string and call .format() with the values to insert. Placeholders can be positional, named, or contain format specifications just like % style.
str.format() Patterns
Three ways to reference values inside .format() placeholders.
- Positional: "{} {}".format("hello", "world") fills left to right
- Indexed: "{0} {1} {0}".format("hip", "hop") reuses positional values
- Named: "{name} is {age}".format(name="Ali", age=25) uses keyword args
- Format spec: "{:.3f}".format(3.14159) rounds to 3 decimal places
- Width: "{:>10}".format("hi") right-aligns in a field of width 10
str.format() Method
PythonPositional, named, and formatted placeholders.
f-strings (Python 3.6+)
f-strings (formatted string literals) are the modern, recommended way to format strings in Python. Prefix a string with f or F and then place any valid Python expression inside curly braces directly in the string. Python evaluates the expression at runtime and inserts the result. f-strings are not just more readable than the older alternatives; they are also faster because the interpolation is done at the C level.
f-string Advantages
f-strings replaced % and .format() as the community standard after Python 3.6.
- More readable: the variable lives right where it appears in the text
- Any expression works inside {}: arithmetic, method calls, ternary, etc.
- Format specs still work: f"{value:.2f}" or f"{value:>10}"
- Python 3.8+ debugging shortcut: f"{x=}" prints x=value automatically
- Cannot span multiple lines by default, use \ or triple-quote raw strings
f-string Formatting
PythonVariables, expressions, method calls, and format specs all work inside {}.
Formatting Numbers (Width and Precision)
Python's format mini-language applies to all three formatting styles and gives you fine control over how numbers are displayed: total field width, decimal precision, alignment, sign display, and thousands separators. These features are essential when building tables, reports, or any output that needs to look aligned and professional.
Format Mini-Language Syntax
The format spec sits after a colon inside the braces: f'{value:spec}'
- Width: f"{42:10d}" pads to 10 characters wide
- Fill and align: f"{42:0>10d}" fills with 0, right-aligned
- < left-align, > right-align, ^ center-align
- .Nf: N decimal places, e.g. f"{3.14159:.2f}" gives 3.14
- ,: thousands separator, e.g. f"{1000000:,}" gives 1,000,000
- +: always show sign, e.g. f"{42:+d}" gives +42
- e: scientific notation, e.g. f"{12345.6:.2e}" gives 1.23e+04
Number Formatting Examples
PythonWidth, precision, alignment, separators, and scientific notation.
Reading Multiple Inputs
Sometimes you need to read several values at once, either on separate lines or all on one line separated by spaces. The standard pattern for a single line of space-separated values is to call input().split() which splits the string on whitespace and returns a list of strings, then pipe that through map() to convert each piece to the required type.
Patterns for Multiple Input
Three common patterns you will use constantly in competitive programming and real scripts.
- Multiple lines: a = int(input()); b = int(input())
- Same line, split: a, b = input().split()
- Same line, convert: a, b = map(int, input().split())
- Unknown count: nums = list(map(int, input().split()))
- Custom separator: values = input().split(",") for comma-separated input
Reading Multiple Inputs
PythonType two numbers separated by a space when prompted.
Command-line Arguments with sys.argv
When you run a Python script from the terminal you can pass extra information directly on the command line: python greet.py Alice 30. Python stores these arguments in a list called sys.argv, available after you import the sys module. The first element sys.argv[0] is always the script name itself; actual user-provided arguments start at index 1.
sys.argv Basics
sys.argv is a list of strings. Every argument, including numbers, comes in as a string.
- sys.argv[0]: the name of the script being run
- sys.argv[1]: the first argument provided by the user
- len(sys.argv) - 1: the number of user-supplied arguments
- All values are strings: convert with int() or float() as needed
- For production CLIs, use the argparse module for richer argument parsing
sys.argv Example
PythonShows how a script receives and uses command-line arguments.
Note: sys.argv reads actual command-line values when you run a .py file in your terminal. The in-browser compiler above will show the script structure but the arguments list will vary in that environment.
Quiz - Test Your Knowledge
Eight questions covering every topic in this tutorial. Work through them carefully before checking your answers.
Knowledge Check
1. What does input() always return in Python 3?
2. Which print() parameter changes the character placed between multiple values?
3. What is the output of: print(f"{3.14159:.2f}")?
4. Which formatting style uses curly braces {} as placeholders?
5. What does sys.argv[0] always contain?
6. How do you read three integers from a single line of input separated by spaces?
7. What does print("a", "b", end="") do differently from a normal print?
8. Which f-string expression pads the number 7 to a width of 5 characters?