Basic Syntax
Input and Output
print() and input() functions
Interview: Basic I/O operations
Python provides built-in functions for console I/O: print() for output and input() for reading user input. For file I/O, see the File Handling chapter.
print() Function
The print() function writes to sys.stdout. It's more powerful than most beginners realize.
sepparameter: separator between values (default: space)endparameter: appended after last value (default: newline)fileparameter: redirect output to any file-like objectflushparameter: force immediate output (useful for progress indicators)
input() Function
input() reads a line from stdin and returns it as a string. Always convert the result if you need a number.
Formatted Output
- f-strings (best):
f"{name} is {age}"— supports expressions, method calls, format specs - format():
"{0} is {1}".format(name, age) - % formatting:
"%s is %d" % (name, age)— legacy style
String Formatting Specifiers
{value:.2f}— 2 decimal places{value:>10}— right-align in 10 chars{value:,}— thousands separator: 1,234,567{value:.0%}— percentage: 75%{value:08b}— binary: 00001010
Use Cases
Building CLI tools with formatted output
Reading and validating user input in interactive programs
Redirecting output to files or stderr for logging
Progress indicators with flush and carriage return
Common Mistakes
Forgetting that input() always returns a string
Not handling ValueError when converting user input to numbers
Using print() for logging instead of the logging module
Forgetting to use flush=True for real-time progress output