print() & input()
Every Python program communicates through two fundamental built-in functions — print() to display output on the screen and input() to receive data from the user. Mastering every parameter and edge case of these two functions gives you complete control over how your programs interact with the world.
The print() Function — Output to the Console
print() is Python's built-in function for displaying
output. It converts its arguments to strings and writes them to the standard output (your terminal/console),
followed by a newline by default. It is the most-used function in Python — every developer runs it dozens of
times every day.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)All parameters except
*objects are optional with sensible defaults.
# 1. Print a string
print("Hello, World!")
# Hello, World!
# 2. Print a number
print(42)
# 42
# 3. Print multiple values (separated by space by default)
print("Name:", "Alice", "Age:", 25)
# Name: Alice Age: 25
# 4. Print any data type — Python converts it to string automatically
print(True) # True
print([1, 2, 3]) # [1, 2, 3]
print({"a": 1}) # {'a': 1}
# 5. Print nothing — blank line
print()
# (empty line)
# 6. Print with concatenation (+ only works with strings)
name = "Alice"
print("Hello, " + name + "!")
# Hello, Alice!
All print() Parameters Explained
print() has 5 parameters. The first (*objects) is
what you want to print. The remaining four control how it prints:
str(). Can be strings, numbers, lists, anything."" to join with no gap, or any other string.\n). Set to "" to stay on
the same line.True, forces the output buffer to flush
immediately. Useful in progress bars or real-time logging where buffered output would cause delays.# ── sep : separator between values (default = space) ──────────
print("a", "b", "c") # a b c
print("a", "b", "c", sep="-") # a-b-c
print("a", "b", "c", sep=", ") # a, b, c
print("a", "b", "c", sep="") # abc
print("a", "b", "c", sep="\n") # a
# b
# c
# Practical: print a date
print(2025, 6, 15, sep="-") # 2025-6-15
# ── end : what to print at the end (default = newline) ────────
print("Hello", end=" ")
print("World") # Hello World ← on same line
print("Loading", end="...")
print("done") # Loading...done
# Loop output on one line
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# ── Combine sep and end together ───────────────────────────────
print("Mon", "Tue", "Wed", sep=" | ", end=" ← days\n")
# Mon | Tue | Wed ← days
# ── file : redirect output to a file ──────────────────────────
import sys
# Print to a text file instead of console
with open("output.txt", "w") as f:
print("This goes to the file", file=f)
print("Second line", file=f)
# Print errors to stderr (standard error stream)
print("Error: file not found", file=sys.stderr)
# ── flush : force immediate output ─────────────────────────────
import time
# Without flush=True the progress bar may not update in real-time
for i in range(5):
print(f"\rProgress: {i+1}/5", end="", flush=True)
time.sleep(0.5)
print() # move to next line when done
Escape Sequences — Special Characters in Strings
An escape sequence is a backslash \
followed by a character that together represent a special character — like a newline, tab, or a quote that
would otherwise end the string.
| Sequence | Name | What it does | Example |
|---|---|---|---|
| \n | Newline | Moves to the next line | print("Hi\nBye") → Hi on line 1, Bye on line 2 |
| \t | Tab | Inserts a horizontal tab (8 spaces) | print("A\tB") →
A B |
| \\ | Backslash | Prints a literal backslash | print("C:\\Users") → C:\Users |
| \' | Single quote | Prints a quote inside a single-quoted string | print('It\'s fine') → It's fine |
| \" | Double quote | Prints a quote inside a double-quoted string | print("Say \"hi\"") → Say "hi" |
| \r | Carriage return | Moves cursor to beginning of current line | Used in progress bars with end="" |
| \0 | Null character | Null byte — rarely used in Python | print("a\0b") → a(null)b |
| \uXXXX | Unicode | Prints the Unicode character at that code point | print("\u2764") → ❤ |
# \n — newline inside a string
print("Line 1\nLine 2\nLine 3")
# Line 1
# Line 2
# Line 3
# \t — tab for column alignment
print("Name\tAge\tCity")
print("Alice\t25\tMumbai")
print("Bob\t30\tDelhi")
# Name Age City
# Alice 25 Mumbai
# Bob 30 Delhi
# \\ — literal backslash (Windows file paths)
print("C:\\Users\\Alice\\Documents")
# C:\Users\Alice\Documents
# r"..." — raw string: backslash NOT treated as escape
print(r"C:\Users\Alice\Documents") # same output, easier to write
# C:\Users\Alice\Documents
# Quotes inside strings
print('She said, "Python is amazing!"') # use outer single quotes
print("It\'s a beautiful day") # escape single quote
# She said, "Python is amazing!"
# It's a beautiful day
# Unicode emoji/symbols
print("\u2764 Python \u2764") # ❤ Python ❤
print("\u2713 Task completed") # ✓ Task completed
r to make it a
raw string. r"C:\new\file.txt" is equivalent to "C:\\new\\file.txt" but much easier to read and write.
F-strings — The Modern Way to Format Output
Introduced in Python 3.6, f-strings (formatted string literals) are the
fastest, most readable way to embed variables and expressions directly inside a string. Prefix the string with
f or F, then place any Python
expression inside { }.
# ── Basic variable embedding ───────────────────────────────────
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
# Name: Alice, Age: 25
# ── Expressions inside {} — any valid Python expression ────────
a, b = 10, 3
print(f"{a} + {b} = {a + b}") # 10 + 3 = 13
print(f"{a} / {b} = {a / b:.2f}") # 10 / 3 = 3.33
print(f"Upper: {name.upper()}") # Upper: ALICE
# ── Number formatting inside {} ────────────────────────────────
pi = 3.14159265
print(f"Pi to 2dp : {pi:.2f}") # Pi to 2dp : 3.14
print(f"Pi to 4dp : {pi:.4f}") # Pi to 4dp : 3.1416
amount = 1234567.89
print(f"Amount: ₹{amount:,.2f}") # Amount: ₹1,234,567.89
print(f"Hex: {255:#x}") # Hex: 0xff
print(f"Binary: {10:b}") # Binary: 1010
print(f"Percent: {0.875:.1%}") # Percent: 87.5%
# ── Alignment and padding ──────────────────────────────────────
print(f"{'left' :<10}|") # left |
print(f"{'right' :>10}|") # | right
print(f"{'center':^10}|") # | center |
print(f"{'num':*^10}") # ****num****
# ── Multi-line f-string ────────────────────────────────────────
item = "Laptop"
price = 45000
qty = 2
receipt = f"""
=== Receipt ===
Item : {item}
Price : ₹{price:,.2f}
Qty : {qty}
Total : ₹{price * qty:,.2f}
==============="""
print(receipt)
.2f = 2
decimal places float. , = thousands separator. % = percentage. b = binary.< left, > right, ^ centre. The number sets
the total width. Fill character goes before the alignment symbol.!r calls repr(), !s calls str(), !a calls ascii(). Useful for debugging."Hello, {}".format(name) or "Hello, %s" % name styles. PEP 498 introduced them in Python 3.6 — always
prefer f-strings in modern Python code.
The input() Function — Reading User Input
input() pauses program execution, displays an
optional prompt to the user, waits for them to type something and press Enter, then returns what
they typed as a string. That last point — always returns a string — is the most
important thing to remember about input().
# 1. Basic input — no prompt
value = input() # waits silently for user to type
# 2. Input with a prompt message
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Example run:
# Enter your name: Alice
# Hello, Alice!
# 3. input() ALWAYS returns a string — check with type()
x = input("Enter a number: ")
print(type(x)) # <class 'str'> — even if user typed 42
# 4. Prompt can be multi-line for readability
city = input(
"Enter your city\n"
"(e.g. Mumbai, Vadodara): "
)
print(f"City: {city}")
# 5. Reading multiple inputs on separate lines
first_name = input("First name: ")
last_name = input("Last name : ")
print(f"Full name: {first_name} {last_name}")
age = input("Age: ") + 5
crashes with TypeError: can only concatenate str (not "int") to str.
Always convert first: age = int(input("Age: ")) + 5.
Type Casting — Converting input() to Numbers
Because input() always returns a string, you must explicitly convert
the result to the type you need. Python provides built-in casting functions: int(), float(), bool(), and str().
# ── Cast to int ────────────────────────────────────────────────
age = int(input("Enter your age: "))
print(f"In 10 years you will be {age + 10}")
# Enter your age: 25
# In 10 years you will be 35
# ── Cast to float ──────────────────────────────────────────────
price = float(input("Enter price (₹): "))
tax = price * 0.18
print(f"Price with 18% GST: ₹{price + tax:.2f}")
# Enter price (₹): 1000
# Price with 18% GST: ₹1180.00
# ── Safe casting with try/except ───────────────────────────────
try:
score = int(input("Enter score (0-100): "))
print(f"Your score: {score}")
except ValueError:
print("Invalid! Please enter a whole number.")
# ── Cast back to string for concatenation ──────────────────────
num = 42
print("The answer is: " + str(num)) # The answer is: 42
# ── Multiple values on one line ────────────────────────────────
# Ask user: "3 5" → split → ["3","5"] → map to int → [3, 5]
a, b = map(int, input("Enter two numbers: ").split())
print(f"Sum = {a + b}")
# Enter two numbers: 10 20
# Sum = 30
# ── List of numbers from one input line ────────────────────────
nums = list(map(int, input("Enter numbers: ").split()))
print(f"Numbers: {nums}")
print(f"Sum: {sum(nums)}")
# Enter numbers: 5 10 15 20
# Numbers: [5, 10, 15, 20]
# Sum: 50
ValueError if user types a decimal like 3.5 or non-numeric text. Always wrap with try/except in production code."42"
and "42.5". Use when you need decimal numbers from the user."10 20 30".split() → ["10", "20", "30"]. Combine with map(int, ...) to convert all at once.int() to every element of an
iterable. map(int, ["10","20"]) → equivalent to [10, 20]. Wrap in list() to get a
list.Advanced Usage — Formatting & Validation
Here are common professional patterns using print() and input() that you will encounter in real Python projects:
# ── Formatted table using f-string alignment ───────────────────
students = [
("Alice", 95, "A"),
("Bob", 82, "B"),
("Carol", 77, "C"),
]
# Header
print(f"{'Name' :<10} {'Score':>6} {'Grade':^6}")
print("-" * 26)
# Rows
for name, score, grade in students:
print(f"{name:<10} {score:>6} {grade:^6}")
# Name Score Grade
# --------------------------
# Alice 95 A
# Bob 82 B
# Carol 77 C
# ── Keep asking until valid input is received ──────────────────
def get_int(prompt, min_val=None, max_val=None):
"""Ask for an integer, retry until user provides a valid one."""
while True:
try:
value = int(input(prompt))
if min_val is not None and value < min_val:
print(f" Must be ≥ {min_val}. Try again.")
elif max_val is not None and value > max_val:
print(f" Must be ≤ {max_val}. Try again.")
else:
return value
except ValueError:
print(" Invalid! Enter a whole number.")
age = get_int("Enter age (1-120): ", 1, 120)
score = get_int("Enter score (0-100): ", 0, 100)
print(f"Age: {age}, Score: {score}")
# Write output directly to a text file with print()
with open("report.txt", "w", encoding="utf-8") as f:
print("=== Monthly Report ===", file=f)
print(f"Total Sales : ₹{125000:,}", file=f)
print(f"Total Orders: {450}", file=f)
print(f"Avg Order : ₹{125000/450:,.2f}", file=f)
print("Report saved to report.txt") # this still goes to console
Mini Projects — print() & input() in Action
The best way to master these functions is to build real programs. Here are three mini projects that combine everything from this chapter:
Project 1 — Simple Calculator
print("═══════════ Python Calculator ═══════════")
print("Operations: + - * / // % **")
print("════════════════════════════════════════")
try:
a = float(input("First number : "))
op = input("Operator : ").strip()
b = float(input("Second number: "))
if op == "+": result = a + b
elif op == "-": result = a - b
elif op == "*": result = a * b
elif op == "/": result = a / b
elif op == "//": result = a // b
elif op == "%": result = a % b
elif op == "**": result = a ** b
else: raise ValueError("Unknown operator")
print(f"\n {a} {op} {b} = {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError as e:
print(f"Error: {e}")
Project 2 — Shopping Bill Generator
GST = 0.18 # 18% GST
items = []
print("╔══════════ Shopping Bill ═══════════╗")
n = int(input("How many items? "))
for i in range(n):
name = input(f" Item {i+1} name : ")
price = float(input(f" Item {i+1} price: ₹"))
items.append((name, price))
subtotal = sum(p for _, p in items)
tax = subtotal * GST
total = subtotal + tax
print("\n╔══════════════════════════════════╗")
print(f" {'ITEM' :<20} {'PRICE':>8}")
print(" " + "─" * 30)
for name, price in items:
print(f" {name:<20} ₹{price:>7,.2f}")
print(" " + "─" * 30)
print(f" {'Subtotal':<20} ₹{subtotal:>7,.2f}")
print(f" {'GST (18%)':<20} ₹{tax:>7,.2f}")
print(" " + "═" * 30)
print(f" {'TOTAL':<20} ₹{total:>7,.2f}")
print("╚══════════════════════════════════╝")
Project 3 — Student Grade Report
name = input("Student name: ")
n = int(input("Number of subjects: "))
scores = []
for i in range(n):
s = float(input(f" Score for subject {i+1} (out of 100): "))
scores.append(s)
avg = sum(scores) / n
# Determine grade
if avg >= 90: grade, emoji = "A+", "🏆"
elif avg >= 80: grade, emoji = "A", "⭐"
elif avg >= 70: grade, emoji = "B", "✅"
elif avg >= 60: grade, emoji = "C", "📘"
else: grade, emoji = "F", "❌"
print(f"\n{'═'*35}")
print(f" Report Card — {name}")
print(f"{'─'*35}")
for i, score in enumerate(scores, 1):
print(f" Subject {i}: {score:5.1f}")
print(f"{'─'*35}")
print(f" Average : {avg:.2f}")
print(f" Grade : {grade} {emoji}")
print(f"{'═'*35}")
- print() signature:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) - sep controls the separator between multiple values (default: space). end controls what comes after all values (default: newline).
- Escape sequences:
\n= newline,\t= tab,\\= backslash,\"= quote. User"..."for raw strings (no escape processing). - F-strings
f"..."are the modern way to format output — embed any expression inside{ }, use format specs like:.2f,:,,:>10for alignment. - input() always returns a
str— even if the user types a number. Always cast withint()orfloat()when you need a numeric type. - Use
try/except ValueErroraround type casting to handle invalid input gracefully without crashing. map(int, input().split())reads multiple space-separated integers from one input line — very common in coding challenges.- Use
print(file=f)to redirect output to a file. Useflush=Truefor real-time terminal output like progress indicators.
The terminal is a text-based interface — everything typed is captured as a stream of
characters. input() has no way to know whether the user intends to enter a number, a date, a name, or
anything else — that interpretation is the programmer's responsibility. So Python's design decision is
correct: always return a string and let the programmer convert it to the appropriate type. When you
need a number, you must explicitly cast: int(input()) or float(input()). Always wrap in try/except ValueError to handle cases where the user types non-numeric
text.
sep is the string inserted between multiple values passed to print().
Default is a single space. Example: print("a","b","c", sep="-") →
a-b-c.
end is the string appended after all values have
been printed. Default is '\n' (newline). Example: print("Hello", end=" ") followed by print("World") outputs Hello World
on a single line — the second print's newline is already handled.
Think of it this way: sep handles what goes inside one print call; end handles what comes after the entire print call finishes.
F-strings win on three fronts:
- Readability:
f"Hello, {name}!"is immediately obvious. Compare to"Hello, {}!".format(name)or"Hello, %s!" % name— you have to look back and forth between the placeholder and the value. - Performance: Benchmarks consistently show f-strings are faster than .format() and % — they are evaluated at parse time, not at runtime string formatting.
- Power: F-strings support any Python expression inside
{ }including function calls, arithmetic, method calls, and format specs.
PEP 498 introduced f-strings in Python 3.6 (2016). All modern Python code should use them exclusively.
The pattern is: a, b = map(int, input("Enter two numbers: ").split())
Step by step: input() returns a string
like "10 20". Calling .split()
on it gives the list ["10", "20"]. Passing that to map(int, ...) applies int() to
each element, yielding the integers 10 and 20. The tuple unpacking a, b = ...
assigns them to variables. For a list of any length use nums = list(map(int, input().split())).
\n is an escape sequence inside a string — it
embeds a newline character at that exact position within the string. For example print("Line 1\nLine 2") outputs two lines from a single print call.
The \n is processed when Python reads the string literal.
end='\n' is a parameter of
print() itself — it controls what character(s) are appended automatically after print
finishes outputting all its arguments. The default is '\n' which
is why each print() call normally starts a new line. Setting end="" suppresses that automatic newline entirely.
Key: \n adds newlines inside
your output; end controls what comes after all your
output.
print("a", "b", "c", sep="-", end="!")input() always return, regardless of
what the user types?3.14159 as
3.14?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.