User Input and Output
# User Input and Output
Welcome to Chapter 6! So far, our programs have used hardcoded values. Now it's time to make them interactive by accepting input from users.
---
1. Introduction
Real-world programs interact with users. A login form asks for credentials. A calculator asks for numbers. In Python, the input() function makes this possible.
---
2. Learning Objectives
-
Use the
input()function to get user input.
- Convert input to appropriate data types.
-
Format output using f-strings,
.format(), and%operator.
- Use escape characters and raw strings.
- Build a user profile generator.
---
3. The input() Function
```python id="py6_ex1" name = input("Enter your name: ") print(f"Hello, {name}!")
python id="py6_ex2" age = int(input("Enter your age: ")) height = float(input("Enter height (m): ")) print(f"Age: {age}, Height: {height}")
python id="py6_ex3" a, b = map(int, input("Enter two numbers: ").split()) print(f"Sum: {a + b}")
python id="py6_ex4" name = "Alice" age = 25 gpa = 3.856
print(f"Name: {name}, Age: {age}") print(f"GPA: {gpa:.2f}") print(f"Formatted: {1234567:,}") print(f"Percentage: {0.856:.1%}") print(f"{'Left':<15}|{'Center':^15}|{'Right':>15}|") print(f"Padded: {42:05d}")
python id="py6_ex5" print("Hello, {}! Age: {}".format("Bob", 30)) print("{name} is {age}".format(name="Alice", age=25))
python id="py6_ex6" print("Line 1\nLine 2") print("Name\tAge") path = r"C:\Users\folder" # Raw string print(path)
python id="py6project" print("=" * 50) print(" 👤 USER PROFILE GENERATOR") print("=" * 50)
firstname = input(" First name: ") lastname = input(" Last name: ") age = int(input(" Age: ")) email = input(" Email: ") city = input(" City: ")
username = f"{firstname.lower()}.{lastname.lower()}{age}"
print("\n" + "=" * 50) print(f"{'GENERATED PROFILE':^50}") print("=" * 50) print(f" {'Full Name':<15}: {firstname} {last_name}") print(f" {'Username':<15}: {username}") print(f" {'Age':<15}: {age}") print(f" {'Email':<15}: {email}") print(f" {'City':<15}: {city}") print(f" {'Status':<15}: {'Minor 🔒' if age < 18 else 'Adult ✅'}") print("=" * 50)
python id="py6ex7" print(f"{'STORE RECEIPT':^40}") print("=" * 40)
items = [("Apples", 3, 1.50), ("Bread", 1, 2.99), ("Milk", 2, 3.49)] total = 0
print(f"{'Item':<15}{'Qty':>5}{'Price':>10}{'Total':>10}") print("-" * 40)
for name, qty, price in items: linetotal = qty * price total += linetotal print(f"{name:<15}{qty:>5}${price:>9.2f}${linetotal:>9.2f}")
print("-" * 40)
print(f"{'GRAND TOTAL':>30}${total:>9.2f}")
``
---
8. Common Mistakes
-
1.
Forgetting to convert input: input()
returns strings. Useint()orfloat().
-
2.
Forgetting the f
prefix:"{name}"prints literally, not the variable value.
-
3.
Not handling invalid input: int("abc")
crashes with ValueError.
-
4.
Escape characters in paths: Use raw strings r"C:\path"
.
---
9. Best Practices
- Use f-strings — fastest and most readable.
- Validate input before converting types.
-
Use .strip()
to remove whitespace:input("Name: ").strip().
- Provide clear prompts to users.
---
10. Exercises
- 1. Build a tip calculator (bill + tip percentage).
- 2. Create a BMI calculator (weight kg, height m).
- 3. Write a temperature converter (Celsius ↔ Fahrenheit).
- 4. Build a formatted student report card.
- 5. Create an interactive quiz with scoring.
---
11. MCQs with Answers
Q1: input() returns:
A) int B) float C) str D) depends
Answer: C
Q2: How to get integer input?
A) input(int) B) int(input()) C) input().int() D) integer(input())
Answer: B
Q3: :.2f in f-string does:
A) Rounds to 2 ints B) 2 decimal places C) Pads 2 zeros D) Multiplies by 2
Answer: B
Q4: Raw string prefix is: A) f B) r C) b D) s Answer: B
Q5: f"{'hi':>10}" produces:
A) hi-------- B) --------hi C) ----hi---- D) hi
Answer: B
Q6: split() does:
A) Joins B) Splits to list C) Removes chars D) Converts case
Answer: B
Q7: int("abc") causes:
A) Returns 0 B) Returns None C) ValueError D) Returns "abc"
Answer: C
Q8: \t produces:
A) New line B) Tab C) Backspace D) Alert
Answer: B
Q9: Best formatting method in modern Python: A) % B) .format() C) f-strings D) Templates Answer: C
Q10: To hide password input, use: A) input() B) getpass() C) hiddeninput() D) secureinput() Answer: B
---
12. Interview Questions
-
1.
Difference between input() in Python 2 vs 3? Python 3 input()
always returns string. Python 2input()evaluates the expression.
- 2. Why are f-strings preferred? More readable, concise, and faster than alternatives.
- 3. How to handle invalid input? Use try-except blocks with ValueError.
-
4.
Difference between print() and return? print()
outputs to console;returnsends value back from function.
-
5.
What are raw strings? Strings prefixed with r
that treat backslashes as literal characters.
---
13. FAQs
Q: Can f-strings contain conditions?
A: Yes! f"{'pass' if score >= 60 else 'fail'}" works.
Q: How to read from file instead of keyboard?
A: File handling (Chapter 16) or redirect: python script.py < input.txt.
---
14. Summary
-
input()
returns strings; convert with int(),float().
- f-strings are the modern formatting method.
- Use escape characters for special output.
- Use raw strings to ignore escapes.
- Always validate user input.
---
15. Next Chapter Recommendation
In Chapter 7: Conditional Statements, you'll learn decision-making with if, elif, else`, and build a grade calculator! 🚀