Quiz 2

Input, Output & Formatted Strings

2258 words
11 min read
Python Week 1: the first filter for runtime behavior
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:
  1. Use input() to read user input from the keyboard
  2. Convert user input to numbers for calculations
  3. Use f-strings to embed variables inside text
  4. Control output with sep, end, and escape sequences
  5. 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:
pseudo
Hello Alice
How it works:
  1. Python reaches input() and pauses — it waits for the user to type something and press Enter.
  2. Whatever the user types is returned as a string.
  3. 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 with int() or float().

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"):
pseudo
Enter 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 in name.
  • 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"):
pseudo
What 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"):
pseudo
Enter 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:
pseudo
Hello, Alice! You are 25 years old.
How it works:
  • The f before the opening quote marks it as an f-string (formatted string).
  • Inside the string, {name} is replaced by the value of the name variable.
  • {age} is replaced by the value of age.
  • You can put expressions inside {} too: {age + 1} would print 26.

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:
pseudo
pi = 3.1415926535
pi = 3.14
pi = 3.1416
pi =      3.14
Population: 1,234,567
Format SpecifierMeaningExample
:.2fRound to 2 decimal places (float){3.14159:.2f}3.14
:.0fRound to 0 decimal places{3.8:.0f}4
:>10Right-align in width 10{"hi":>10}hi
:<10Left-align in width 10{"hi":<10}hi
:^10Center 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):
pseudo
Enter 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:
pseudo
apple 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:
pseudo
Line 1
Line 2
Tab	separated
Backslash: \
Quote: "Hello"
Single: 'Hello'
EscapeEffect
\nNewline (jumps to next line)
\tTab (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):
pseudo
Quick Math Quiz
====================
What is 12 + 8? 20
Correct!
What is 7 * 6? 42
Correct!
Your final score: 2/2
Percentage: 100%

📐 Key Concepts Reference

ConceptSyntaxPurposeExample
User inputinput()Read text from keyboardname = input("Name: ")
User input (number)int(input())Read a numberage = int(input("Age: "))
F-stringf"{var}"Embed variables in textf"Hello {name}"
F-string formatf"{val:.2f}"Control decimal placesf"${price:.2f}"
Print separatorprint(a, b, sep=",")Custom gap between itemssep=" - "
Print endprint("x", end="")Custom line endingend=" " (no newline)
Newline\nJump to new line in stringprint("a\nb")
Tab\tInsert tab spaceprint("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"?
python
name = input()
print("Hello", name)
Answer:
pseudo
World
Hello World
  • The user types "World" (pressed Enter).
  • input() returns "World", stored in name.
  • print("Hello", name) prints "Hello" followed by a space, then "World". Q2: Identify the error:
python
age = input("Age: ")
print("Next year you'll be", age + 1)
Answer: Error: TypeError: can only concatenate str (not "int") to str Fix: Convert input to int: age = int(input("Age: ")) input() returns a string. Adding 1 to a string is not allowed. Q3: What does this code output?
python
price = 49.956
print(f"Price: ${price:.2f}")
Answer:
pseudo
Price: $49.96
The format specifier :.2f rounds to 2 decimal places. Note: 49.956 rounds to 49.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?
python
print("A", "B", "C", sep="-", end="!")
Answer:
pseudo
A-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 \n and \t do in a string?
Answer:
  • \n inserts a newline (moves to the next line).
  • \t inserts a tab (like pressing Tab key).
python
print("Item\tPrice\nApple\t$1.00")
Output:
pseudo
Item	Price
Apple	$1.00
Q8: 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?
python
print(f"Value = {10/3:.2f}")
Answer: Nothing! This code is correct. It outputs Value = 3.33. The f-string evaluates 10/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

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.