๐ฆ Python Fundamentals
Module 2 ยท Topic 4
Input & Output Mastery
Master reading user input with input(), advanced print() usage, and all three string formatting methods.
Theory
The input() Function:
- Always returns a string, regardless of what the user types
- Blocks execution until user presses Enter
- Optional prompt message:
input("Enter name: ") - Must explicitly convert for numbers:
int(input(...))
The print() Function โ Advanced Usage:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)sep: separator between multiple argumentsend: what to print at the end (default: newline)file: output destination (can write to files)flush: force immediate output (useful for progress indicators)
Three String Formatting Methods:
-
f-strings (Python 3.6+, RECOMMENDED):
f"Name: {name}, Age: {age}"- Can contain expressions:
f"{2**10}" - Format specs:
f"{3.14159:.2f}",f"{42:05d}"
- Can contain expressions:
-
.format() method:
"Name: {}, Age: {}".format(name, age)
"Name: {0}, Age: {1}".format(name, age) -
% operator (oldest, C-style):
"Name: %s, Age: %d" % (name, age)
Common Format Specifiers:
:.2fโ 2 decimal places:05dโ zero-padded to 5 digits:>10โ right-aligned in 10 chars:<10โ left-aligned in 10 chars:^10โ centered in 10 chars:,โ thousands separator:%โ percentage
Syntax
# Input
name = input("Enter name: ") # Always returns str
age = int(input("Enter age: ")) # Convert to int
# Output with f-string
print(f"Hello {name}, you are {age} years old")
# Format specifiers
print(f"{price:.2f}") # 2 decimals
print(f"{num:05d}") # Zero-padded
print(f"{val:>10}") # Right-aligned