Python Notes
Python mein user se input lena aur output dikhana — input(), print(), f-strings, formatting, file I/O basics aur real-world input handling ke saath complete guide.
Hindi: Input/Output (I/O) matlab user se data lena aur user ko data dikhana.input()se user se data lete hain aurprint()se display karte hain — yeh Python programming ke do sabse basic operations hain.
2. String Formatting Methods
Method 1: f-Strings (Python 3.6+ — Recommended)
Hindi: f-strings sabse modern aur easy tarika hai — string ke pehleflagate hain aur curly braces{}mein variable likhte hain.
name = "Rahul"
age = 25
salary = 75000.50
is_manager = True
# Basic f-string
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Salary: ₹{salary}")
# Expressions in f-strings
print(f"Birth year: {2026 - age}")
print(f"Monthly take-home: ₹{salary * 0.7:.2f}")
# Method calls
print(f"Upper name: {name.upper()}")
print(f"Name length: {len(name)}")
# Conditional expression
print(f"Role: {'Manager' if is_manager else 'Employee'}")Name: Rahul Age: 25 Salary: ₹75000.5 Birth year: 2001 Monthly take-home: ₹52500.35 Upper name: RAHUL Name length: 5 Role: Manager
Method 2: .format() Method
# Positional arguments
print("Hello, {}! You are {} years old.".format("Priya", 22))
# Named arguments
print("{name} lives in {city}.".format(name="Amit", city="Delhi"))
# Numbered placeholders
print("{0} + {1} = {2}".format(5, 3, 5+3))
print("{0} {1} {0}".format("wow", "Python")) # reuseHello, Priya! You are 22 years old. Amit lives in Delhi. 5 + 3 = 8 wow Python wow
Method 3: % Formatting (Old Style)
name = "Rahul"
age = 25
gpa = 3.87
print("Name: %s, Age: %d, GPA: %.2f" % (name, age, gpa))
print("Hex: %x, Octal: %o" % (255, 255))Name: Rahul, Age: 25, GPA: 3.87 Hex: ff, Octal: 377
3. Format Specifiers
# Number formatting with f-strings
pi = 3.14159265358979
big = 1234567.89
small = 0.000123
# Decimal places
print(f"pi = {pi:.2f}") # 2 decimal places
print(f"pi = {pi:.4f}") # 4 decimal places
print(f"pi = {pi:.0f}") # 0 decimal places (rounds)
# Width
print(f"|{pi:10.2f}|") # width 10, right-aligned
print(f"|{pi:<10.2f}|") # left-aligned
print(f"|{pi:^10.2f}|") # center-aligned
# Thousands separator
print(f"Big: {big:,.2f}") # with comma
print(f"Big: {big:_.2f}") # with underscore (Python 3.6+)
# Scientific notation
print(f"Small: {small:.2e}")
print(f"Big: {big:.3E}")
# Percentage
rate = 0.0875
print(f"Tax rate: {rate:.1%}") # as percentagepi = 3.14 pi = 3.1416 pi = 3 | 3.14| |3.14 | | 3.14 | Big: 1,234,567.89 Big: 1_234_567.89 Small: 1.23e-04 Big: 1.235E+06 Tax rate: 8.8%
# String formatting
text = "Python"
print(f"|{text:10}|") # width 10, left-aligned (default for str)
print(f"|{text:>10}|") # right-aligned
print(f"|{text:^10}|") # centered
print(f"|{text:*<10}|") # fill with *
print(f"|{text:─^20}|") # fill with ─ and center|Python | | Python| | Python | |Python****| |───────Python───────|
# Integer formatting
n = 255
print(f"Decimal: {n:d}") # decimal
print(f"Binary: {n:b}") # binary
print(f"Octal: {n:o}") # octal
print(f"Hex: {n:x}") # hex lowercase
print(f"Hex: {n:X}") # hex uppercase
print(f"With prefix: {n:#x}") # hex with 0x prefix
print(f"With prefix: {n:#b}") # binary with 0b prefix
# Padded with zeros
print(f"Zero-padded: {n:08b}") # 8 digits, zero-padded
print(f"Zero-padded: {n:04X}") # 4 hex digits, zero-paddedDecimal: 255 Binary: 11111111 Octal: 377 Hex: ff Hex: FF With prefix: 0xff With prefix: 0b11111111 Zero-padded: 11111111 Zero-padded: 00FF
4. The input() Function
Hindi: input() user se keyboard se text input leta hai. Yeh hamesha string return karta hai — number chahiye toh convert karna padega!# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")Enter your name: Rahul Hello, Rahul!
Input Always Returns String!
# THIS IS A VERY COMMON BEGINNER MISTAKE!
age = input("Enter your age: ") # user types: 20
print(type(age)) # <class 'str'> — NOT int!
# year = 2026 - age # ❌ TypeError: can only concatenate str to str
# CORRECT WAY — convert to appropriate type:
age = int(input("Enter your age: "))
birth_year = 2026 - age
print(f"You were born in {birth_year}")Enter your age: 20 <class 'str'> Enter your age: 25 You were born in 2001
Multiple Inputs on One Line
# Method 1: split() — space-separated
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"{x} + {y} = {x + y}")Enter two numbers (space-separated): 10 20 10 + 20 = 30
# Method 2: map() — cleaner approach
a, b, c = map(int, input("Enter 3 numbers: ").split())
print(f"Sum: {a + b + c}")
print(f"Average: {(a + b + c) / 3:.2f}")Enter 3 numbers: 15 25 35 Sum: 75 Average: 25.00
# Method 3: List of inputs
n = int(input("How many numbers? "))
numbers = list(map(int, input("Enter numbers: ").split()))
print(f"Numbers: {numbers}")
print(f"Sum: {sum(numbers)}")
print(f"Max: {max(numbers)}")
print(f"Min: {min(numbers)}")How many numbers? 5 Enter numbers: 3 7 2 9 5 Numbers: [3, 7, 2, 9, 5] Sum: 26 Max: 9 Min: 2
Custom Separator Input
Enter subjects (comma-separated): Math, Science, English, Hindi Subjects: ['Math', 'Science', 'English', 'Hindi'] Count: 4
5. Input Validation
Hindi: User har waqt sahi input nahi deta — isliye input validate karna zaroori hai. Try-except use karte hain invalid input handle karne ke liye.
# Safe integer input with validation
def get_integer(prompt, min_val=None, max_val=None):
"""Get a validated integer from user."""
while True:
try:
value = int(input(prompt))
if min_val is not None and value < min_val:
print(f"⚠️ Value must be at least {min_val}")
continue
if max_val is not None and value > max_val:
print(f"⚠️ Value must be at most {max_val}")
continue
return value
except ValueError:
print("❌ Invalid input! Please enter a whole number.")
# Usage
age = get_integer("Enter your age (1-120): ", 1, 120)
print(f"✅ Age accepted: {age}")Enter your age (1-120): abc ❌ Invalid input! Please enter a whole number. Enter your age (1-120): 150 ⚠️ Value must be at most 120 Enter your age (1-120): 25 ✅ Age accepted: 25
# Yes/No input
def get_yes_no(prompt):
"""Get a yes/no response from user."""
while True:
response = input(prompt + " (yes/no): ").strip().lower()
if response in ("yes", "y"):
return True
elif response in ("no", "n"):
return False
else:
print("Please enter 'yes' or 'no'")
is_student = get_yes_no("Are you a student?")
print(f"Is student: {is_student}")Are you a student? (yes/no): maybe Please enter 'yes' or 'no' Are you a student? (yes/no): yes Is student: True
6. Advanced Print Formatting
Table Formatting
╔════════════════╦═══════╦═════════╦══════════╦═════════╗ ║ Name ║ Math ║ Science ║ English ║ Average ║ ╠════════════════╬═══════╬═════════╬══════════╬═════════╣ ║ Rahul Kumar ║ 85 ║ 92 ║ 78 ║ 85.0 ║ ║ Priya Sharma ║ 90 ║ 88 ║ 95 ║ 91.0 ║ ║ Amit Singh ║ 72 ║ 80 ║ 68 ║ 73.3 ║ ║ Neha Gupta ║ 95 ║ 97 ║ 92 ║ 94.7 ║ ╚════════════════╩═══════╩═════════╩══════════╩═════════╝
Pretty Print (pprint)
--- Normal print ---
{'name': 'WoHo Academy', 'location': 'Delhi', 'classes': {'10th': {'sections': ['A', 'B', 'C'], ...}}}
--- pprint ---
{'classes': {'10th': {'sections': ['A', 'B', 'C'],
'students': 120,
'teachers': ['Mr. Sharma',
'Ms. Gupta',
'Mr. Verma']},
'11th': {'sections': ['A', 'B'],
'students': 80,
'teachers': ['Dr. Mehta',
'Ms. Kapoor']}},
'location': 'Delhi',
'name': 'WoHo Academy'}7. Real-World Application — Interactive Student Form
def get_student_info():
"""Interactive form to collect student information."""
print("=" * 50)
print(" STUDENT REGISTRATION FORM")
print("=" * 50)
# Text inputs
name = input("Full Name: ").strip().title()
roll = input("Roll Number: ").strip()
# Integer with validation
while True:
try:
age = int(input("Age: "))
if 5 <= age <= 25:
break
print("Age must be between 5 and 25!")
except ValueError:
print("Please enter a valid number!")
# Float with validation
while True:
try:
marks = float(input("Total Marks (out of 500): "))
if 0 <= marks <= 500:
break
print("Marks must be between 0 and 500!")
except ValueError:
print("Please enter a valid number!")
# Calculate
percentage = (marks / 500) * 100
if percentage >= 90:
grade = "A+"
elif percentage >= 80:
grade = "A"
elif percentage >= 70:
grade = "B"
elif percentage >= 60:
grade = "C"
else:
grade = "D"
# Display result
print("\n" + "=" * 50)
print(" REGISTRATION SUCCESSFUL")
print("=" * 50)
print(f" Name: {name}")
print(f" Roll: {roll}")
print(f" Age: {age}")
print(f" Marks: {marks:.0f}/500")
print(f" Percentage: {percentage:.2f}%")
print(f" Grade: {grade}")
print("=" * 50)
# Run the form
get_student_info()==================================================
STUDENT REGISTRATION FORM
==================================================
Full Name: rahul kumar
Roll Number: 2301
Age: 17
Total Marks (out of 500): 425
==================================================
REGISTRATION SUCCESSFUL
==================================================
Name: Rahul Kumar
Roll: 2301
Age: 17
Marks: 425/500
Percentage: 85.00%
Grade: A
==================================================8. Format Specifier Quick Reference
| Specifier | Meaning | Example | Output |
|---|---|---|---|
{:d} | Integer | {42:d} | 42 |
{:f} | Float | {3.14:f} | 3.140000 |
{:.2f} | 2 decimal places | {3.14159:.2f} | 3.14 |
{:e} | Scientific notation | {12345:e} | 1.234500e+04 |
{:s} | String | {"hello":s} | hello |
{:b} | Binary | {10:b} | 1010 |
{:o} | Octal | {8:o} | 10 |
{:x} | Hex | {255:x} | ff |
{:X} | HEX | {255:X} | FF |
{:%} | Percentage | {0.75:%} | 75.000000% |
{:.1%} | Percentage 1dp | {0.75:.1%} | 75.0% |
{:10} | Width 10 | {"hi":10} | hi |
{:>10} | Right-align | {"hi":>10} | hi |
{:^10} | Center | {"hi":^10} | hi |
{:0>5} | Zero-pad | {42:0>5} | 00042 |
{:,} | Thousands sep | {1234567:,} | 1,234,567 |
Practice Exercises
Exercise 1 — Formatted Receipt
Create a shopping receipt printer:
- Input: item name, price, quantity (3 items)
- Output: formatted table with subtotals, GST (18%), and grand total
Exercise 2 — Number Converter
Build an interactive number base converter:
- Input: decimal number
- Output: show it in binary, octal, hexadecimal (nicely formatted)
Exercise 3 — Student Grade Calculator
Input marks for 5 subjects using map(int, input().split()). Calculate and display: total, percentage, grade, pass/fail.
Interview Questions
Q1. Why does input() always return a string? > input() reads raw text from the keyboard. Python can't know whether the user intends to enter a number, name, or date — it treats everything as text (str). The programmer must explicitly convert using int(), float() etc.
Q2. What are the advantages of f-strings over .format()? > f-strings (Python 3.6+) are more readable (expressions inline), faster (evaluated at runtime, not via .format() parsing), support complex expressions, method calls, and format specs all in one place: f"{value:.2f}" vs "{:.2f}".format(value).
Q3. How do you print without a newline in Python? > Use print("text", end="") — the end parameter defaults to "\n". Set it to "" for no newline, " " for space, or any custom string.
Q4. How do you take multiple space-separated integers as input in Python? > a, b, c = map(int, input().split()) — split() splits by whitespace, map(int, ...) applies int() to each part, unpacking assigns to variables.
Q5. What is the difference between print(x) and print(repr(x))? > print(x) uses str(x) — human-readable, no quotes for strings. print(repr(x)) uses repr(x) — programmer representation, adds quotes for strings, shows escape sequences. Use repr() for debugging: print(repr("\n")) shows '\\n' instead of a blank line.
⚠️ Common Mistakes
Mistake 1: input() ka result directly number ki tarah use karna ❌
# ❌ WRONG — input() hamesha string return karta hai!
age = input("Enter age: ")
new_age = age + 1 # TypeError: can only concatenate str (not "int") to str
# ✅ CORRECT — pehle int() ya float() mein convert karo
age = int(input("Enter age: "))
new_age = age + 1 # Works perfectly!Mistake 2: print() mein comma aur + ka confusion 🤯
name = "Rahul"
age = 25
# ❌ WRONG — + se string aur int join nahi hote
# print("Age: " + age) # TypeError!
# ✅ CORRECT — comma use karo ya f-string
print("Age:", age) # comma automatically space add karta hai
print(f"Age: {age}") # f-string best approach haiMistake 3: split() ke baad values ka count mismatch 💥
# ❌ WRONG — agar user 2 values de aur aap 3 expect karo
# x, y, z = input("Enter: ").split() # ValueError agar 2 values di!
# ✅ CORRECT — pehle list mein lo, phir check karo
values = input("Enter numbers: ").split()
if len(values) == 3:
x, y, z = valuesMistake 4: f-string mein quotes ka galat usage 🔤
name = "Rahul"
# ❌ WRONG — same quotes inside f-string expression
# print(f"Hello {"World"}") # SyntaxError!
# ✅ CORRECT — different quotes use karo
print(f"Hello {'World'}") # single inside double
print(f'Name: {name + " Kumar"}') # double inside singleMistake 5: sep aur end ka misuse 🔄
# ❌ WRONG — sep sirf multiple arguments ke beech kaam karta hai
print("Hello World", sep="-") # No effect! Single argument hai
# ✅ CORRECT — multiple arguments do
print("Hello", "World", sep="-") # Output: Hello-WorldMistake 6: File mein print karne ke baad file close na karna 📂
# ❌ RISKY — file close na karna data loss kar sakta hai
# f = open("log.txt", "w")
# print("Log entry", file=f)
# (bhool gaye close karna!)
# ✅ CORRECT — with statement use karo (auto-close)
with open("log.txt", "w") as f:
print("Log entry", file=f)
# File automatically close ho jati haiMistake 7: \n ko escape na karna print mein 🪲
# ❌ Unexpected output — path mein \n newline ban jata hai
# print("C:\new_folder\test") # \n = newline, \t = tab!
# ✅ CORRECT — raw string ya double backslash
print(r"C:\new_folder\test") # raw string (r prefix)
print("C:\\new_folder\\test") # escaped backslash✅ Key Takeaways
- 📌
print()Python ka primary output function hai —sep,end, aurfileparameters se flexible control milta hai - 📌
input()hamesha string return karta hai — number operations ke liyeint()yafloat()se convert karna zaroori hai - 📌 f-strings (Python 3.6+) sabse modern, readable, aur fastest formatting method hai — interviews mein yeh recommend karo
- 📌 Format specifiers (
:.2f,:>10,:,,:#x) se numbers aur strings ko professionally format kar sakte ho - 📌 Multiple inputs ek line mein lene ke liye
split()+map()combo use karo:a, b = map(int, input().split()) - 📌 Input validation production code mein must hai —
try-exceptke saathwhile Trueloop lagao taaki invalid input pe program crash na ho - 📌
pprintmodule complex nested data structures (dict, list) ko readable format mein dikhata hai — debugging ke liye perfect - 📌 File I/O ke liye
with open()hamesha use karo — yeh file ko automatically close karta hai, memory leak nahi hoti - 📌
end=""parameter se same line pe multiple prints kar sakte ho — progress bars aur loading animations ke liye useful - 📌
repr()vsstr(): debugging ke liyerepr()use karo kyunki yeh escape characters aur quotes dikhata hai
❓ FAQ
Q1. Kya input() se directly integer le sakte hain bina convert kiye? > ❌ Nahi! Python 3 mein input() hamesha string return karta hai. Aapko explicitly int(input()) ya float(input()) likhna padega. Python 2 mein raw_input() aur input() alag the — but Python 3 mein sirf input() hai jo string deta hai.
Q2. print() aur sys.stdout.write() mein kya difference hai? > print() automatically newline add karta hai, multiple arguments le sakta hai, sep/end parameters hote hain. sys.stdout.write() sirf ek string accept karta hai, koi newline nahi add karta, aur characters ka count return karta hai. Performance-critical code mein sys.stdout.write() thoda faster ho sakta hai.
Q3. f-string mein curly braces {} literally kaise print karein? > Double curly braces use karo: f"{{value}}" will print {value} literally. Triple braces mein outer pair escape hota hai aur inner pair expression hota hai: f"{{{name}}}" prints {Rahul}.
Q4. input() ke through password (hidden input) kaise lein? > getpass module use karo: from getpass import getpass phir user_input = getpass("Enter: ") likho. Yeh terminal pe typed characters hide kar deta hai — security ke liye best practice. Note: Kuch IDEs (like IDLE, Jupyter) mein yeh properly kaam nahi karta, terminal/CMD mein best hai.
Q5. print() ka flush=True kab use karte hain? > Jab aapko output turant screen pe dikhana ho bina buffer ke. Normally Python output buffer karta hai. Progress bars, real-time logs, ya long-running processes mein print("Working...", flush=True) use karo taaki text immediately dikhe.
Q6. Ek line mein unknown number of inputs kaise lein? > List comprehension ya map() use karo: numbers = list(map(int, input().split())). Yeh space-separated inputs ko integer list mein convert karega. Count pehle se fix karne ki zaroorat nahi — user jitne bhi numbers de, sab list mein aa jayenge.
Q7. format() function aur .format() method mein kya fark hai? > format(value, spec) ek built-in function hai jo single value format karta hai: format(3.14, '.1f') → '3.1'. .format() string method hai jo poori string mein multiple placeholders fill karta hai: "{} + {}".format(2, 3). f-strings dono ka kaam ek jagah karte hain!
Q8. File mein output write karne ke liye print(file=f) better hai ya f.write()? > Dono kaam karte hain lekin use case alag hai. print(file=f) automatically newline add karta hai aur multiple arguments, formatting support karta hai — quick logging ke liye best. f.write() precise control deta hai — exact bytes likhta hai, koi extra newline nahi. Large data writing mein f.write() slightly faster hai.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Input and Output.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, input, output
Related Python Master Course Topics