Chapter 4: Console I/O

Master console input and output: print(), input(), and various string formatting techniques.

Download chapter4.py

Objectives

1. The print() Function

Print values to console. Default sep=' ', end='\n':

print("Hello", "World")           # Hello World
print("No newline", end="")           # stays on same line
print(" → next")

Customize separator and flush:

print(1, 2, 3, sep=" - ")          # 1 - 2 - 3
import sys
print("Immediate", flush=True)         # flushes buffer

2. The input() Function

Prompt the user and read a line (returns str):

name = input("Enter your name: ")
age_str = input("Enter your age: ")
age = int(age_str)                    # convert to int
print(f"Name: {name}, Age: {age}")

Always handle conversion errors:

try:
    num = int(input("Number: "))
except ValueError:
    print("Invalid number!")

3. String Formatting

a) f-strings (Python 3.6+)

user = "Alice"
score = 95.5
print(f"{user} scored {score:.1f} points")

b) str.format()

template = "{} has {} apples"
print(template.format("Bob", 3))

c) % Operator

fmt = "Total: %d items, %0.2f$"
print(fmt % (7, 15.239))

Exercises

  1. Write a script that asks for three numbers, prints their sum.
  2. Prompt for first/last name separately and greet with an f-string.
  3. Build a small menu: ask “1) Add 2) Subtract”, read choice, perform on two inputs.