A. Programming Concepts and Skills · Programming Basics: Data, Decisions and LoopsInput, 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 numbersheight = 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.
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
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 exampleExample 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.
- Plan with the IPO chart above: input
price (float); processing tax = price * HST_RATE and total = price + tax; output both, formatted. - Put the constant near the top:
HST_RATE = 0.13. - Read and convert in one line:
price = float(input("Price before tax: $")). - Use f-strings with
:.2f for money. - 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 exampleExample 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.
- Read both names with
input(). They are already strings, so no conversion is needed. - Concatenate:
username = first + "." + last + str(11). The number must be converted with str() (or written as the string "11"). - The banner is string repetition: twenty copies of
"=". - 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 funWhy 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 activityRecipe scaler
You need: a recipe from a cookbook, a box or a family card (pancakes, muffins, bannock or anything you like), and Python.
- 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. - Write the program. Store the original servings and 3 or 4 ingredient amounts in variables (in mL, g or number of eggs).
- Use
float(input(...)) for the number of servings wanted. - Print a heading with string repetition and each ingredient with an f-string, rounded to 1 decimal place with
:.1f. - 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
1What is the type of x after this line, if the user types 7?
str. x is "7". input() always returns a string.
2Write one line that reads a temperature in degrees Celsius that may have decimals, and stores it as a number.
celsius = float(input("Temperature in °C: "))
3What is "ab" + "cd"? What is three copies of "ab" made with repetition?
4What does print(f"{2.5:.2f}") show? What about print(f"{1500000:,}")?
5Write a program that asks for the length and width of a rectangular rink in metres and prints the area with a label.
Sample:
length = float(input("Length (m): "))width = float(input("Width (m): "))area = length * widthprint(f"Area: {area} square metres")
For 60 and 26 it prints Area: 1560.0 square metres.
6Find and fix the error. The user types 4.
n = input("How many? ")print(n * 2)
No crash, but the output is 44, because n is the string "4" and a string times 2 is repeated. Fix: n = int(input("How many? ")), so the output is 8.
7Make an IPO chart for a program that converts kilometres to metres.
Input: km (float) from the keyboard. Processing: metres = km * 1000. Output: the number of metres with a label, for example 2.5 km = 2500.0 m.
More practice: warm-up
1What type does input() return?
3What does print("-" * 5) show?
4What letter goes before the quote to make an f-string?
Shows x with exactly 2 decimal places.
More practice: on your own
1What does print(f"{'A':>5}|") show? Count the spaces.
A|: four spaces then A, because the A is right-aligned in a space 5 characters wide.
2Write 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.
Sample:
minutes = int(input("Minutes: "))print(f"{minutes} minutes is {minutes // 60} h {minutes % 60} min")
3What is printed?
word = "ho"line = word * 3 + "!"print(line)
hohoho!. Repetition happens before concatenation (like multiplication before addition).
4Rewrite with an f-string: print("Total: $" + str(round(total, 2))). Why is the f-string better for money?
print(f"Total: ${total:.2f}"). round(total, 2) drops trailing zeros (4.5 prints as 4.5), while :.2f always shows two decimal places (4.50).
5A user enters 12.5 at int(input("Count: ")). What happens, and how could you accept it?
A ValueError, because int() cannot convert the string "12.5". Use float(input(...)) if decimals make sense, or int(float(input(...))) to cut the value to 12.
Challenge
1Write 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.
Sample:
bill = float(input("Bill: $"))percent = float(input("Tip %: "))tip = bill * percent / 100print(f"{'Tip:':<8}{tip:>10.2f}")print(f"{'Total:':<8}{bill + tip:>10.2f}")
With 48.60 and 15: tip 7.29 and total 55.89, both right-aligned.
2Write 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.
Sample:
n = int(input("3-digit number: "))h = n // 100t = n // 10 % 10o = n % 10print(o * 100 + t * 10 + h)print(h + t + o)
For 472 it prints 274 and 13. (str(o) + str(t) + str(h) also reverses it, using concatenation.)
3Explain why print("Total: " + 5) crashes but print("Total:", 5) works.
+ with a string on the left means concatenation, which needs two strings, so the int 5 causes a TypeError. With commas, print receives two separate items and converts each to text itself, putting a space between them.
Check your understandingQuiz
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?
5. In an IPO chart, area = length * width belongs in which column?
6. Which prompt is the most user-friendly?
For parents and teachersBig 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.