Input, Output & Formatted Strings
2258 words
11 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Input, Output & Formatted Strings > **Why read this?** A program that always works with the same data is boring. Real programs interact with users — ask for a name, read a number, then respond.

Input, Output & Formatted Strings
Why read this? A program that always works with the same data is boring. Real programs interact with users — ask for a name, read a number, then respond. This topic teaches you how to make your programs conversational.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Use
input()to read user input from the keyboard - Convert user input to numbers for calculations
- Use f-strings to embed variables inside text
- Control output with
sep,end, and escape sequences - Write programs that respond dynamically to user input
📋 Prerequisites
- Variables & Data Types — You need to understand variables and type conversion.
- Basic understanding of strings (text in quotes).
📖 Core Content
3.1 The input() Function — Getting User Input
What problem does this solve? Instead of hardcoding data inside your program,
input() lets the program pause and wait for the user to type something.python# runnable name = input() print("Hello", name)
If the user types "Alice", the output is:
pseudoHello Alice
How it works:
- Python reaches
input()and pauses — it waits for the user to type something and press Enter. - Whatever the user types is returned as a string.
- That string is assigned to the variable
name.
⚠️ Critical:input()ALWAYS returns a string, even if the user types a number. If you want a number, you must convert it withint()orfloat().
3.2 input() with a Prompt
You can pass a string argument to
input() — it displays that text as a prompt before waiting:python# runnable name = input("Enter your name: ") print("Hello, " + name + "!")
Output (if user types "Bob"):
pseudoEnter your name: Bob Hello, Bob!
Line-by-line:
input("Enter your name: ")— Prints "Enter your name: " then waits for input.- The user types "Bob" and presses Enter.
name = "Bob"— The string "Bob" is stored inname.print("Hello, " + name + "!")— Concatenates (joins) three strings: "Hello, " + "Bob" + "!" = "Hello, Bob!"
3.3 Worked Example 1: Age Calculator
python# runnable name = input("What is your name? ") age_str = input("How old are you? ") age = int(age_str) # convert string to integer next_year = age + 1 print("Hello", name + "!") print("Next year, you will be", next_year, "years old.")
Output (user types "Alice" then "25"):
pseudoWhat is your name? Alice How old are you? 25 Hello Alice! Next year, you will be 26 years old.
Note: We used
int(age_str) because input() returns a string. Without this conversion, age + 1 would produce a TypeError (can't add string and integer).3.4 Worked Example 2: Number Input — Common Bug
python# runnable number = input("Enter a number: ") result = number * 3 print("Result:", result)
Output (user types "5"):
pseudoEnter a number: 5 Result: 555
What went wrong? The user typed
5, but input() returned the string "5". In Python, multiplying a string by an integer repeats the string. So "5" * 3 is "555".
Fix: Convert to integer first: number = int(input("Enter a number: "))3.5 F-Strings — The Modern Way to Format Text
What problem does this solve? Building strings by concatenation (
"Hello " + name + "!") is messy. F-strings let you embed variables directly inside curly braces {} within a string.python# runnable name = "Alice" age = 25 print(f"Hello, {name}! You are {age} years old.")
Output:
pseudoHello, Alice! You are 25 years old.
How it works:
- The
fbefore the opening quote marks it as an f-string (formatted string). - Inside the string,
{name}is replaced by the value of thenamevariable. {age}is replaced by the value ofage.- You can put expressions inside
{}too:{age + 1}would print26.
3.6 F-String Format Specifiers
You can control HOW values are displayed inside f-strings:
python# runnable pi = 3.1415926535 # Default: full precision print(f"pi = {pi}") # Round to 2 decimal places print(f"pi = {pi:.2f}") # Round to 4 decimal places print(f"pi = {pi:.4f}") # Width of 10 characters, right-aligned print(f"pi = {pi:10.2f}") # Large number with comma separators big = 1234567 print(f"Population: {big:,}")
Output:
pseudopi = 3.1415926535 pi = 3.14 pi = 3.1416 pi = 3.14 Population: 1,234,567
| Format Specifier | Meaning | Example |
|---|---|---|
:.2f | Round to 2 decimal places (float) | {3.14159:.2f} → 3.14 |
:.0f | Round to 0 decimal places | {3.8:.0f} → 4 |
:>10 | Right-align in width 10 | {"hi":>10} → hi |
:<10 | Left-align in width 10 | {"hi":<10} → hi |
:^10 | Center in width 10 | {"hi":^10} → hi |
:, | Comma as thousands separator | {1000000:,} → 1,000,000 |
:.2% | Format as percentage | {0.25:.2%} → 25.00% |
3.7 Worked Example 3: F-String Calculator
python# runnable name = input("Enter your name: ") score1 = float(input("Enter score 1: ")) score2 = float(input("Enter score 2: ")) score3 = float(input("Enter score 3: ")) average = (score1 + score2 + score3) / 3 print(f"\n--- Report for {name} ---") print(f"Average score: {average:.2f}") print(f"Total points: {score1 + score2 + score3:.0f}") print(f"Status: {'Pass' if average >= 50 else 'Fail'}")
Output (user types "Bob", 75, 82, 91):
pseudoEnter your name: Bob Enter score 1: 75 Enter score 2: 82 Enter score 3: 91 --- Report for Bob --- Average score: 82.67 Total points: 248 Status: Pass
Note: F-strings can even contain simple logic like{'Pass' if average >= 50 else 'Fail'}— this is called a ternary expression, which we'll cover in conditionals.
3.8 Controlling print(): sep and end
The
print() function has two useful parameters:sep(separator): What to put between items (default: space)end(ending): What to put at the end (default: newline\n)
python# runnable # Using sep to customize separator print("apple", "banana", "cherry") # default: space print("apple", "banana", "cherry", sep=", ") # comma + space print("apple", "banana", "cherry", sep=" - ") # dash print("apple", "banana", "cherry", sep="") # no separator # Using end to control line endings print("Hello", end=" ") print("World") # prints "Hello World" on same line print("Counting:", end=" ") for i in range(5): print(i, end=", ") # stays on same line
Output:
pseudoapple banana cherry apple, banana, cherry apple - banana - cherry applebananacherry Hello World Counting: 0, 1, 2, 3, 4,
3.9 Escape Sequences
Escape sequences let you insert special characters inside strings:
python# runnable print("Line 1\nLine 2") # \n = newline print("Tab\tseparated") # \t = tab print("Backslash: \\") # \\ = literal backslash print("Quote: \"Hello\"") # \" = literal double quote print("Single: \'Hello\'") # \' = literal single quote
Output:
pseudoLine 1 Line 2 Tab separated Backslash: \ Quote: "Hello" Single: 'Hello'
| Escape | Effect |
|---|---|
\n | Newline (jumps to next line) |
\t | Tab (horizontal) |
\\ | Backslash |
\" | Double quote inside a double-quoted string |
\' | Single quote inside a single-quoted string |
3.10 Worked Example 4: Multi-line Text Display
python# runnable print("=" * 30) print("WELCOME TO THE PROGRAM") print("=" * 30) print() name = input("Enter your name: ") print(f"\nHi {name}, let's calculate your BMI!\n") weight = float(input("Weight (kg): ")) height = float(input("Height (m): ")) bmi = weight / (height ** 2) print(f"\n{'='*30}") print(f"Name: {name}") print(f"BMI: {bmi:.1f}") print(f"{'='*30}")
Output:
javascript============================== WELCOME TO THE PROGRAM ============================== Enter your name: Alice Hi Alice, let's calculate your BMI! Weight (kg): 65 Height (m): 1.7 ============================== Name: Alice BMI: 22.5 ==============================
3.11 Worked Example 5: Interactive Quiz
python# runnable print("Quick Math Quiz") print("=" * 20) answer1 = int(input("What is 12 + 8? ")) score = 0 if answer1 == 20: print("Correct!") score += 1 else: print(f"Oops! The answer was 20.") answer2 = int(input("What is 7 * 6? ")) if answer2 == 42: print("Correct!") score += 1 else: print(f"Oops! The answer was 42.") print(f"\nYour final score: {score}/2") print(f"Percentage: {score/2*100:.0f}%")
Output (user types 20 and 42):
pseudoQuick Math Quiz ==================== What is 12 + 8? 20 Correct! What is 7 * 6? 42 Correct! Your final score: 2/2 Percentage: 100%
📐 Key Concepts Reference
| Concept | Syntax | Purpose | Example |
|---|---|---|---|
| User input | input() | Read text from keyboard | name = input("Name: ") |
| User input (number) | int(input()) | Read a number | age = int(input("Age: ")) |
| F-string | f"{var}" | Embed variables in text | f"Hello {name}" |
| F-string format | f"{val:.2f}" | Control decimal places | f"${price:.2f}" |
| Print separator | print(a, b, sep=",") | Custom gap between items | sep=" - " |
| Print end | print("x", end="") | Custom line ending | end=" " (no newline) |
| Newline | \n | Jump to new line in string | print("a\nb") |
| Tab | \t | Insert tab space | print("a\tb") |
⚠️ Common Pitfalls
Pitfall 1: Forgetting to Convert input()
The mistake:
price = input("Price: ") then total = price * 1.1 The error: TypeError: can't multiply sequence by non-int of type 'float' Why: input() returns a string. You can't multiply a string by a float. Fix: price = float(input("Price: "))Pitfall 2: Using input() inside a Loop Without Understanding
The mistake: Thinking
input() only runs once when inside a loop. What happens: Each iteration of the loop calls input() again, re-prompting the user. This can be confusing if unintended. Fix: Store the input in a variable before the loop if you only need one value.Pitfall 3: F-String Brace Confusion
The mistake: Trying to print literal curly braces with f-strings:
print(f"Variable is {var}") but sometimes you need { or } in the output. Fix: Double the braces for literal ones: print(f"{{Hello}}") prints {Hello}.Pitfall 4: input() Prompt Not Flushing
The mistake:
input("Enter value: ") but the prompt doesn't appear before the program waits. Why: In some environments, the prompt needs a newline to flush. This is rare in modern IDEs/Repl.it. Fix: Use print("Enter value: ", end="") then input() separately, or just know it normally works.📝 Practice Questions
Q1: What will this program output if the user types "World"?pythonname = input() print("Hello", name)Answer:pseudoWorld Hello World
- The user types "World" (pressed Enter).
input()returns"World", stored inname.print("Hello", name)prints "Hello" followed by a space, then "World". Q2: Identify the error:pythonage = input("Age: ") print("Next year you'll be", age + 1)Answer: Error:TypeError: can only concatenate str (not "int") to strFix: Convert input to int:age = int(input("Age: "))input()returns a string. Adding1to a string is not allowed. Q3: What does this code output?pythonprice = 49.956 print(f"Price: ${price:.2f}")Answer:pseudoPrice: $49.96The format specifier:.2frounds to 2 decimal places. Note:49.956rounds to49.96(banker's rounding). Q4: Write a program that asks for the user's name and age, then prints "Hello NAME, you are AGE years old." using an f-string.Answer:python# runnable name = input("Enter your name: ") age = input("Enter your age: ") print(f"Hello {name}, you are {age} years old.")Q5: What's the output?pythonprint("A", "B", "C", sep="-", end="!")Answer:pseudoA-B-C!
sep="-"puts dashes between items.end="!"uses!instead of the default newline. Q6: Write code that reads two numbers, multiplies them, and prints the result formatted as "Result: 12.50".Answer:python# runnable a = float(input("First number: ")) b = float(input("Second number: ")) product = a * b print(f"Result: {product:.2f}")Q7: What does\nand\tdo in a string?Answer:
\ninserts a newline (moves to the next line).\tinserts a tab (like pressing Tab key).pythonprint("Item\tPrice\nApple\t$1.00")Output:pseudoItem Price Apple $1.00Q8: How would you print the string "She said "Hello"" including the quotes?Answer:python# Option 1: Single quotes for outer string print('She said "Hello"') # Option 2: Escape the double quotes print("She said \"Hello\"")Both output:She said "Hello"Q9: What's wrong with this code?pythonprint(f"Value = {10/3:.2f}")Answer: Nothing! This code is correct. It outputsValue = 3.33. The f-string evaluates10/3(≈3.3333) and formats it to 2 decimal places. Q10: Write a program that reads a student's marks in 3 subjects, computes total and percentage, and displays a formatted report card.Answer:python# runnable name = input("Student name: ") s1 = float(input("Subject 1 mark: ")) s2 = float(input("Subject 2 mark: ")) s3 = float(input("Subject 3 mark: ")) total = s1 + s2 + s3 percentage = total / 3 print("\n" + "=" * 30) print(f"REPORT CARD: {name}") print("=" * 30) print(f"Subject 1: {s1:.1f}") print(f"Subject 2: {s2:.1f}") print(f"Subject 3: {s3:.1f}") print("-" * 30) print(f"Total: {total:.1f}") print(f"Percentage: {percentage:.2f}%") print("=" * 30)
🔗 Cross-References
- Next Topic: Operators & Expressions — Deep dive into all Python operators and precedence.
- Previous Topic: Variables & Data Types
- BSCS1001 Computational Thinking: Input/Output connects to the "interaction" phase of computational problem-solving.
- Reference: Python for Everybody, Chapter 2 (Sections 2.9-2.10)
- Video: L13: Variables & input statement, L38: Formatted printing Join Discord Previous2. Variables & TypesNext4. Operators & Expressions