livepython.net
CHAPTER 07Getting Input from the User
7.3  INTERACTIVE

Build Small Interactive Python Programs

Input, Process, Output

Almost every program follows the same three-step shape, called input, process, output (IPO for short):

  1. Input: get the data, here with input().
  2. Process: work with it: convert, calculate, combine.
  3. Output: show the result with print().
  1. Start:
    Start
  2. Input or output:
    Input: read a number
  3. Step:
    Process: multiply it by 2
  4. Input or output:
    Output: show the result
  5. End:
    End
A program that doubles a number

You know these shapes from chapter 3: input and output are parallelograms, and the processing step is a rectangle. Now each shape becomes one line of code:

PYTHONedit me
number = int(input())
double = number * 2
print("Double:", double)
OUTPUT
Double: 42

Think of a juice machine: fruit goes in (input), the machine squeezes it (process), and juice comes out (output).

Plan before you code

For every program in this topic, start by answering three questions:

  • What goes in? Which values does the user type, and are they text, whole numbers or decimals?
  • What happens? Which calculation or combination?
  • What comes out? What exactly should the screen show?

Once you can answer them, the code is just three short groups of lines. This is the 4-step method from chapter 3, made concrete.

Input, process, output: plan all three, then write the code.

your turnOrder the lines

Put the lines in input, process, output order

  1. with_tax = price * 1.18
  2. print(f"With tax: {with_tax:.2f}")
  3. price = float(input())

The user types: 100

These lines are mixed up. Put them back in order, then press Check.

A Personal Greeting Program

Let's build a complete program that greets the user and tells them their age next year.

Plan:

  • In: a name (text) and an age (a whole number).
  • Process: add 1 to the age.
  • Out: a friendly message.
PYTHONedit me
name = input()
age = int(input())
next_age = age + 1
print(f"Hello, {name}!")
print(f"Next year you will be {next_age}.")
OUTPUT
Hello, Sunny!
Next year you will be 15.

Try it with your own name and age.

What each line does

LineStep
name = input()input: text, so no conversion
age = int(input())input: converted to a whole number
next_age = age + 1process
the two print() linesoutput, with f-strings

Make it your own

Change the program so it also says how many years until they turn 100:

PYTHONedit me
name = input()
age = int(input())
print(f"{name}, you will be 100 in {100 - age} years.")
OUTPUT
Rocky, you will be 100 in 70 years.

The calculation sits right inside the f-string, as you learned in chapter 5.

Think of this program as a birthday card machine: give it a name and an age, and it writes the card for you.

A complete program: read the inputs, work with them, then show a clear message.

your turnType the output

Type what this prints

name = input() age = int(input()) print(f"{name} will be {age + 1}")

The user types: Lucky9

Read the code line by line, then type the output exactly.

A Simple Calculator

Now a calculator: the user types two numbers, and the program shows what you get with each operator.

Plan:

  • In: two numbers, possibly with decimals, so float().
  • Process: add, subtract, multiply and divide.
  • Out: one line per operation.
PYTHONedit me
a = float(input())
b = float(input())
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
OUTPUT
8.0 + 2.0 = 10.0
8.0 - 2.0 = 6.0
8.0 * 2.0 = 16.0
8.0 / 2.0 = 4.0

Each line shows the full sum, so the user can check it. Because we used float(), every number shows a .0.

Whole numbers only?

If the calculator is only for whole numbers, use int() and the extra operators from chapter 5:

PYTHONedit me
a = int(input())
b = int(input())
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
OUTPUT
17 // 5 = 3
17 % 5 = 2

What could go wrong?

If the user types 0 as the second number, the division stops with a ZeroDivisionError. In chapter 8, you'll check for that with if before dividing.

Common beginner doubt: "Why does 8 show as 8.0?" Because float() turned it into a decimal number, and Python always shows floats with a point. Use int() if you only want whole numbers.

Think of this program as a pocket calculator with only one button: "show me everything".

A calculator is input (two numbers), process (the operators) and output (one line each).

your turnFill the gap

Make it print the remainder

a = int(input()) b = int(input()) print(a ? b)

The user types: 175

It should print: 2

Which piece makes this code work?

A Unit Converter

Converters are perfect input programs: a value goes in, a formula changes it, and the new value comes out.

Kilometres to miles

One kilometre is about 0.621371 miles.

PYTHONedit me
km = float(input())
miles = km * 0.621371
print(f"{km} km is {miles:.2f} miles")
OUTPUT
10.0 km is 6.21 miles

Notice the named value: miles = km * 0.621371. You could write 0.621371 straight into the print(), but a clear name makes the code easier to read and to check, as you learned in the Comments chapter.

Minutes to hours and minutes

With // and % from chapter 5, you can split a number into parts:

PYTHONedit me
total = int(input())
hours = total // 60
minutes = total % 60
print(f"{total} minutes is {hours} h {minutes} min")
OUTPUT
135 minutes is 2 h 15 min

Think of changing money: 135 rupees in 60-rupee notes is 2 notes, with 15 rupees left over. That's // and %.

Check your converter

Test with a value whose answer you know: 60 minutes should give 1 h 0 min, and 0 km should give 0 miles. If those are right, try the tricky ones.

A converter reads a value, applies a formula, and shows the result neatly.

your turnPredict the output

What will this print?

total = int(input()) print(total // 60, total % 60)

The user types: 125

Your turn! What will this code show on the screen?
your turnFix the code

Make it convert 5 km correctly

It should print: 5000 metres

The user types: 5

km = input()
print(km * 1000, "metres")
This code does not work yet. Fix it, then press Run.

Practice: Interactive

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 56.Python Program to Calculate Age in MonthsEasySolve
  2. 57.Python Program to Split a Bill Between FriendsMediumSolve
  3. 58.Python Program to Make a Shopping Receipt from InputHardSolve