Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Input, Processing and Output with String Expressions

A2.1 A1.3 A1.1About 70 minutes
Learning goals
  • I can read keyboard input with input() and convert it to the right type.
  • I can plan a program with an IPO (input, processing, output) chart.
  • I can build strings with concatenation (+) and repetition.
  • I can format output with f-strings, including 2 decimal places.
  • I can write a complete program that reads input, processes it and displays clear output.

Words to know

input()
A built-in function that shows a prompt, waits for the user to type and press Enter, and returns what was typed as a string.
prompt
The message that tells the user what to type, such as "Enter your age: ".
concatenation
Joining strings end to end with +: "snow" + "ball" is "snowball".
string repetition
Repeating a string with an asterisk and a whole number, for example three copies of "ha" give "hahaha".
f-string
A string with f before the opening quote. Expressions inside { } are replaced by their values.
format specifier
Instructions after a colon inside { } that control how a value is shown, such as :.2f for 2 decimal places.
IPO chart
A planning table listing a program's inputs, processing steps and outputs.

Programs that listen

So far your programs have done the same thing every time. Real programs respond to the user: a bank machine asks for an amount, a game asks for your name, a recipe app asks how many people are coming. This lesson completes the input → process → output model from Lesson 1.

Reading input

input(prompt) shows the prompt, waits for the user to type something and press Enter, and returns what was typed as a string.

  • name = input("What is your name? ")

End the prompt with a space so the user's typing does not touch the question.

The most important rule: input() always returns a string. If the user types 16, you get "16". To calculate with it, convert it right away:

  • age = int(input("Age: ")) for whole numbers
  • height = float(input("Height in metres: ")) for decimals

If you forget, "16" + 1 crashes with a TypeError. And input() + input() with 16 and 1 gives "161": the strings are joined, not added.

you type1 6 Enterinput() returns"16" (str)int(...)converts16(int)age = int(input("Age: "))one line: read the text, then convert it to a number
input() always gives back a string, even when the user types digits. Wrap it in int() or float() to get a number you can calculate with.
name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello,", name)
print("In 5 years you will be", age + 5)

A sample run. The user typed Noor and 16. Output, line by line: What is your name? Noor | How old are you? 16 | Hello, Noor | In 5 years you will be 21 (the typed input is shown after each prompt)

Planning with an IPO chart

Before writing code, list:

  • Input: what the user gives the program, with a data type for each.
  • Processing: the calculations or decisions, written as formulas.
  • Output: exactly what the user should see, and how it is formatted.

This short plan catches mistakes early and makes the code almost write itself. It is the input-process-output model that professional developers use when they design software.

String expressions

In A1.3 you must use assignment with string expressions as well as arithmetic ones. Strings have two operators:

  • Concatenation + joins strings: full = first + " " + last. Both sides must be strings, so convert numbers first: "Level " + str(3).
  • Repetition: a string times a whole number repeats it. "=" * 20 is a line of 20 equal signs, handy for headings.

You can build a string step by step: message = "", then message += "Snow ", then message += "day!". (More tools for working inside strings, such as taking out one character or a piece, are in the unit Arrays and Subprograms.)

Formatted output with f-strings

Joining many pieces with + and str() gets messy. An f-string is easier: put f before the quote and write any variable or expression inside { }.

  • print(f"{name} is {age} years old.")
  • print(f"Next year: {age + 1}")

Add a format specifier after a colon to control the look:

  • {price:.2f} shows exactly 2 decimal places (money): 4.5 becomes 4.50.
  • {big:,} adds thousands separators: 1234567 becomes 1,234,567.
  • {word:>8} right-aligns in a space 8 characters wide; {word:<8} left-aligns. Useful for tables.
item = "toque"
price = 24.5
qty = 3
print("=" * 24)
print(f"{qty} x {item} at ${price:.2f}")
print(f"Subtotal: ${qty * price:.2f}")
print(f"{'Item':<8}{'Cost':>8}")
print(f"{item:<8}{price:>8.2f}")

String repetition makes the line. :.2f shows cents, and <8 and >8 line up columns. (Inside an f-string with double quotes, use single quotes for any strings in the braces.) Output, line by line: ======================== | 3 x toque at $24.50 | Subtotal: $73.50 | Item Cost | toque 24.50

Inputprice (float)from the keyboardProcessingtax = price * HST_RATEtotal = price + taxOutputtax and total,2 decimal placesconstant: HST_RATE = 0.13
An IPO chart plans a program before you write it: what comes in, what is calculated, and what goes out. This one plans Example 1.
Worked example

Example 1: An HST calculator

Write a program that asks for the price of an item, then prints the HST (13%) and the total, each to 2 decimal places, with clear labels.

  1. Plan with the IPO chart above: input price (float); processing tax = price * HST_RATE and total = price + tax; output both, formatted.
  2. Put the constant near the top: HST_RATE = 0.13.
  3. Read and convert in one line: price = float(input("Price before tax: $")).
  4. Use f-strings with :.2f for money.
  5. Test with a value you can check by hand: $100 should give $13.00 tax and $113.00 total.

See the program and sample run below. For a price of 39.99, the tax is $5.20 (5.1987 rounded) and the total is $45.19.

# File: hst.py
# Purpose: Calculates Ontario HST and total price.
HST_RATE = 0.13
price = float(input("Price before tax: $"))
tax = price * HST_RATE
total = price + tax
print(f"HST: ${tax:.2f}")
print(f"Total: ${total:.2f}")

Example 1, with a sample run. Output, line by line: Price before tax: $39.99 | HST: $5.20 | Total: $45.19 (the typed input is shown after each prompt)

Worked example

Example 2: Building a string

Ask the user for a first name and a last name. Print a username made of the first name in full, a dot, the last name and the number 11, with no spaces (for example jo.singh11). Then print the greeting Welcome, jo.singh11! between two banners made of 20 equal signs.

  1. Read both names with input(). They are already strings, so no conversion is needed.
  2. Concatenate: username = first + "." + last + str(11). The number must be converted with str() (or written as the string "11").
  3. The banner is string repetition: twenty copies of "=".
  4. Print the banner, then the greeting with an f-string, then the banner again.

With inputs jo and singh, the username is jo.singh11. See the program below.

first = input("First name: ")
last = input("Last name: ")
username = first + "." + last + str(11)
banner = "=" * 20
print(banner)
print(f"Welcome, {username}!")
print(banner)

Example 2 as a program. Output, line by line: First name: jo | Last name: singh | ==================== | Welcome, jo.singh11! | ==================== (the typed input is shown after each prompt)

Just for fun

Why did the program say Mia would be 161 next year?

It never converted her input: "16" + "1" is "161". Always convert numbers from input().

Hands-on activity

Recipe scaler

You need: a recipe from a cookbook, a box or a family card (pancakes, muffins, bannock or anything you like), and Python.

  1. Write an IPO chart on paper: the input is the number of servings wanted; the processing multiplies each ingredient by wanted / original servings; the output lists each ingredient with its new amount.
  2. Write the program. Store the original servings and 3 or 4 ingredient amounts in variables (in mL, g or number of eggs).
  3. Use float(input(...)) for the number of servings wanted.
  4. Print a heading with string repetition and each ingredient with an f-string, rounded to 1 decimal place with :.1f.
  5. Test it with the original number of servings (amounts should not change), with double, and with half.

What to look for: with the original number of servings, the scale factor is 1 and every amount prints unchanged. For a recipe for 4 that uses 250 mL of flour, 6 servings should show 375.0 mL. A good program has a header comment, clear prompts, and amounts lined up in a neat list. (Ask a grown-up before actually cooking anything.)

Your turn

1

What is the type of x after this line, if the user types 7?

  • x = input("Number: ")
2

Write one line that reads a temperature in degrees Celsius that may have decimals, and stores it as a number.

3

What is "ab" + "cd"? What is three copies of "ab" made with repetition?

4

What does print(f"{2.5:.2f}") show? What about print(f"{1500000:,}")?

5

Write a program that asks for the length and width of a rectangular rink in metres and prints the area with a label.

6

Find and fix the error. The user types 4.

  • n = input("How many? ")
  • print(n * 2)
7

Make an IPO chart for a program that converts kilometres to metres.

More practice: warm-up

1

What type does input() return?

2

What is "Go" + "!"?

3

What does print("-" * 5) show?

4

What letter goes before the quote to make an f-string?

5

What does {x:.2f} do?

More practice: on your own

1

What does print(f"{'A':>5}|") show? Count the spaces.

2

Write a program that asks for a number of minutes (whole number) and prints it in hours and minutes, for example 135 minutes is 2 h 15 min.

3

What is printed?

  • word = "ho"
  • line = word * 3 + "!"
  • print(line)
4

Rewrite with an f-string: print("Total: $" + str(round(total, 2))). Why is the f-string better for money?

5

A user enters 12.5 at int(input("Count: ")). What happens, and how could you accept it?

Challenge

1

Write a program that reads a bill amount and a tip percentage (for example 15), and prints the tip and the total, each with 2 decimal places, lined up in a column 10 characters wide.

2

Write a program that reads a 3-digit whole number and prints it with its digits reversed (472 → 274) using arithmetic only, then prints the sum of the digits.

3

Explain why print("Total: " + 5) crashes but print("Total:", 5) works.

Check your understanding

Quiz

1.

The user types 20 at x = input("Age: "). What is x + x?

2.

Which line correctly reads a whole number?

3.

What does print(f"${3.1:.2f}") show?

4.

What is "ab" * 2 + "c"?

5.

In an IPO chart, area = length * width belongs in which column?

6.

Which prompt is the most user-friendly?

For parents and teachers

Big idea: expectation A2.1 asks students to write programs with user input, processing and screen output. String expressions (concatenation and repetition) complete A1.3.

How to help: be the user! Run your teen's program and type unexpected things: a decimal where a whole number is expected, a word instead of a number, or nothing at all. Talk about what the program should do in each case (Lesson 11 shows how to ask again when a number is out of range; handling a word instead of a number needs exception handling, which comes in the unit Software Development).

Common difficulties:

  • Forgetting to convert input, so + joins text instead of adding numbers.
  • Converting with int() when the user may type decimals.
  • Unclear prompts with no space at the end.
  • Rounding money with round() and getting 4.5 instead of 4.50. Use :.2f.