Skip to content

Showing output and reading input

~15 min ยท prerequisite: Installing and running Python

What you will be able to do

  • Show text and numbers on the screen with print, and control the spacing between them.
  • Ask the user a question with input and store the answer in a variable.
  • Convert the text from input into a number before you do maths with it.

The idea

A program needs two directions of communication. It must output results to the person running it, and it must read input, which is information the person types. In Python, the function print does the output, and the function input does the reading.

print takes any number of values, shows them on one line, and then moves to a new line. It puts a single space between values by default. You can change that space with the sep argument, and you can change the ending with end. An argument is a value you pass to a function inside its parentheses. sep and end are named arguments, so you write them as sep=" " and end="\n".

input shows an optional message, waits until the person types a line and presses Enter, and then gives back what they typed. The result is always a string, which is text, even if the person typed digits. The text "12" and the number 12 look alike on the screen, but Python treats them differently. Lesson 4 explains types in detail. For now, remember that input always returns text.

If you want to do arithmetic on the answer, you must convert it. The function int turns text such as "12" into the integer 12. The function float turns text such as "2.5" into a decimal number. If the text is not a valid number, the conversion fails, and the program stops with an error.

Two important points for this lesson. First, input blocks: the program stops and waits until the person answers. Second, the code examples that use input cannot run inside this course's browser runner, so they appear as plain code blocks. Run them in your terminal, where you can type an answer.

Worked example

Save this as greet.py and run it with python3 greet.py.

name = input("What is your name? ")
print("Hello,", name)

Line by line, this is what Python does:

  1. input("What is your name? ") shows the question on the screen and waits. The space at the end of the question keeps the cursor from touching the text you type.
  2. When you type a name and press Enter, input returns that name as a string, and the assignment stores it in the variable name.
  3. print("Hello,", name) receives two values, the text "Hello," and the value of name. It shows them separated by one space.

If you type Ada and press Enter, the output is:

What is your name? Ada
Hello, Ada

Now a program that does arithmetic on the answer.

age_text = input("How old are you? ")
age = int(age_text)
print("Next year you will be", age + 1)

The line age = int(age_text) converts the text into an integer. Without that step, age_text + 1 would fail, because you cannot add a number to text.

Try it

The blocks below do not wait for a person, so they can run in the browser. Each one captures what print writes, using a helper from the standard library, and checks it with assert.

import io
from contextlib import redirect_stdout

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("Hello", "world")
assert buffer.getvalue() == "Hello world\n"

This block changes the separator and the ending.

import io
from contextlib import redirect_stdout

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("2024", "01", "15", sep="-", end="!")
assert buffer.getvalue() == "2024-01-15!"

This block shows the conversion step without a real question. In a real program, the string would come from input.

answer = "42"
number = int(answer)
assert number + 1 == 43
assert answer + "1" == "421"

Common mistakes

  1. Forgetting the quotes around text. Writing print(Hello) tells Python to look for a variable named Hello:

    NameError: name 'Hello' is not defined
    

    Write print("Hello") instead.

  2. Adding a number to the result of input. The following code fails when the person types a number:

    age = input("Age? ")
    print(age + 1)
    
    TypeError: can only concatenate str (not "int") to str
    

    Convert first with age = int(input("Age? ")).

  3. Converting text that is not a number. int("twelve") gives:

    ValueError: invalid literal for int() with base 10: 'twelve'
    

    The conversion needs digits only, such as "12".

  4. Misspelling the function name. Writing prnt("Hi") gives:

    NameError: name 'prnt' is not defined. Did you mean: 'print'?
    

    Python sometimes adds a hint. Read the hint, then correct the spelling.

  5. Leaving out a closing bracket. Writing print("Hi" gives:

    SyntaxError: '(' was never closed
    

Practice

  1. Write a program that prints your favorite word, then prints the number 7 on the next line.
  2. Write a program that prints a, b, and c on one line, separated by a comma and a space, so the output is a, b, c. Hint: use sep.
  3. Write a program that asks for a name with input and prints Welcome, followed by that name. Run it and type your name.
  4. Write a program that asks for a number, converts it with int, and prints the number multiplied by 3. Test it with 4.
  5. Stretch: write a program that asks for two numbers as text, converts both to integers, and prints their sum on one line in the form Sum: 9 when the answers are 4 and 5.
Solution
  1. python print("tea") print(7)

  2. python print("a", "b", "c", sep=", ")

  3. python name = input("Name? ") print("Welcome,", name)

The output keeps the comma after Welcome because print adds one space between the two values.

  1. python number = int(input("Number? ")) print(number * 3)

With the answer 4, the output is 12.

  1. python first = int(input("First number? ")) second = int(input("Second number? ")) print("Sum:", first + second)

With the answers 4 and 5, the output is Sum: 9.

Recap

  • print shows values on one line and moves to a new line. Use sep and end to change the spacing.
  • input waits for the person to type, then returns the answer as a string.
  • Use int or float to turn text into a number before you do maths with it.

Sources