[8.1.3] Input & Output
[8.1.3] Input & Output (I/O)
Input brings data into a program from the user or another source; output presents results back to the user or to another destination. Mastering I/O is essential because it turns isolated calculations into useful, interactive programs. In IGCSE tasks you will commonly read values from the keyboard and write results to the screen. You will also need to handle data types correctly, format messages clearly, and combine I/O with validation and control structures.
Core ideas: prompts, reading, converting, and displaying
- Prompting: a short, clear message that tells the user what to enter, including units where helpful (e.g. "Enter length in centimetres:").
- Reading: get the user's keystrokes; most languages read text initially. If you need a number, convert it.
- Converting: cast the text to the required type (INTEGER/REAL) before using it in arithmetic.
- Displaying: present outputs with labels, units, and sensible formatting (e.g. two decimal places for money).
Console I/O patterns (compare common scenarios)
Below are three frequent I/O scenarios you will meet. Use the tabs to see how each is handled and what to watch out for.
Numeric input with type conversion
Keyboard input is read as text. If you need arithmetic, convert to a numeric type first. Failing to convert causes string behaviour (e.g. concatenation) instead of addition.
// CAIE Pseudocode
DECLARE a : REAL, b : REAL, total : REAL
OUTPUT "Enter first number:"
INPUT a // some environments read numeric directly; if not, convert
OUTPUT "Enter second number:"
INPUT b
total ← a + b
OUTPUT "Sum = " & total
# Python
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
total = a + b
print("Sum =", total)
Tip: If your language reads everything as STRING, convert explicitly before arithmetic.
String input with trimming & case
When reading text, remove accidental spaces and normalise case before comparing. This makes your program more forgiving of user typing.
// CAIE Pseudocode
DECLARE ans : STRING
OUTPUT "Continue? (Y/N): "
INPUT ans
ans ← UPPER(ans) // normalise
ans ← TRIM(ans) // remove surrounding spaces
IF ans = "Y" THEN
OUTPUT "Continuing..."
ELSE
OUTPUT "Stopping."
ENDIF
# Python
ans = input("Continue? (Y/N): ").strip().upper()
if ans == "Y":
print("Continuing...")
else:
print("Stopping.")
Tip: Use functions like TRIM, UPPER or their language equivalents to tidy input before using it.
Formatted output (labels & decimals)
Outputs should be readable. Include labels, units, and control decimal places when displaying monetary values or measurements.
// CAIE Pseudocode
DECLARE price : REAL ← 12.5
OUTPUT "Total price: £" & FORMAT(price, 2) // two decimal places
# Python
price = 12.5
print(f"Total price: £{price:.2f}")
Tip: Fixed two decimal places are standard for currency; more may be needed for science measurements.
I/O with validation (good prompts reduce errors)
Clear prompts reduce invalid entries. Even so, programs should check user input and ask again when it is not acceptable. This improves robustness and user experience.
Presence & type checks
Ensure the user enters something, and that it can be converted to the required type. If not, re-prompt.
// CAIE Pseudocode
DECLARE ageText : STRING
DECLARE age : INTEGER
REPEAT
OUTPUT "Enter your age (whole number): "
INPUT ageText
IF ageText = "" THEN
OUTPUT "You must enter something."
ELSEIF ISINTEGER(ageText) = FALSE THEN
OUTPUT "Please enter digits only."
ENDIF
UNTIL ageText <> "" AND ISINTEGER(ageText) = TRUE
age ← TOINTEGER(ageText)
OUTPUT "Next year you will be " & (age + 1)
// Python (one simple approach)
while True:
age_text = input("Enter your age (whole number): ").strip()
if age_text == "":
print("You must enter something.")
continue
if not age_text.isdigit():
print("Please enter digits only.")
continue
age = int(age_text)
break
print("Next year you will be", age + 1)
Range checks for numbers
Values often need to be within limits. Perform a range check after converting to a number.
// CAIE Pseudocode
DECLARE mark : INTEGER
REPEAT
OUTPUT "Enter mark (0–100): "
INPUT mark
UNTIL mark >= 0 AND mark <= 100
OUTPUT "Mark recorded."
# Python
while True:
mark = int(input("Enter mark (0–100): "))
if 0 <= mark <= 100:
break
print("Out of range, try again.")
print("Mark recorded.")
Menu input: validating options
When the user must choose one option, validate against a set of allowed values. Show the menu clearly so the user knows what to enter.
// CAIE Pseudocode
DECLARE choice : STRING
REPEAT
OUTPUT "1) Add 2) Delete 3) Quit"
OUTPUT "Enter choice (1,2,3): "
INPUT choice
UNTIL choice = "1" OR choice = "2" OR choice = "3"
OUTPUT "You selected option " & choice
# Python
while True:
print("1) Add 2) Delete 3) Quit")
choice = input("Enter choice (1,2,3): ").strip()
if choice in ("1","2","3"):
break
print("Invalid option.")
print("You selected option", choice)
Designing clear I/O for user experience
Think about the human at the keyboard. Good I/O design prevents confusion and speeds up tasks:
- Be specific: include units and ranges ("Enter height in cm (50–250):").
- Be consistent: use the same wording and layout for similar prompts.
- Be forgiving: accept lower/upper case, ignore extra spaces, and handle minor mistakes kindly.
- Be informative: when rejecting input, state why and how to fix it.
Deep Dive: Sequencing I/O with control structures
I/O rarely stands alone. It is usually paired with selection and iteration to build useful dialogue with a user.
- Input → Process → Output: the standard pattern. Read values, calculate, then display a labelled result.
- Input → Validate (loop) → Process → Output: when bad input is likely, repeat the prompt until the data is acceptable.
- Menu loop: repeatedly show a menu, perform actions based on the choice, until the user picks Quit.
Common I/O pitfalls and fixes
| Pitfall | Consequence | Fix |
|---|---|---|
| Not converting text to numbers | Concatenation instead of arithmetic; run-time errors | Cast to INTEGER/REAL before calculations |
| Vague prompts | Users enter the wrong thing | Include example, units, and valid range in the prompt |
| Ignoring spaces/case | Correct entries rejected | Trim spaces and normalise case before comparisons |
| Unformatted numbers | Hard-to-read output | Control decimal places and include labels/units |
Key Takeaways
- Input reads text by default in many languages; convert to the correct data type before processing.
- Clear prompts and informative error messages make programs easier to use and reduce mistakes.
- Validate presence, type, range, and options to improve robustness.
- Format output with labels, units, and suitable decimal places.
- Combine I/O with loops and selection to build interactive, user-friendly programs.