Menu

Programming Fundamentals

Output

Contents

  1. The print Function
  2. Printing Strings
  3. Printing Numbers and Expressions
  4. Printing Multiple Items with Commas
  5. String Concatenation
  6. Working Out Program Output
  7. Common Output Errors

Output is data a program sends out: information for whoever is using it, such as text on the screen, numbers in a console window or a sound from the speakers. It is how a program reports back what it has done, so almost every program you write will produce some.

In Python 3, output is produced with the built-in print function. Its name is written in lower case and is followed by a pair of brackets holding the item or items you want to output. Whatever sits between those brackets is what reaches the screen.

What can go in the brackets

A print call can output a string of text, a plain number, a variable (the value it currently holds is output), or a calculation, where the result is sent to the screen rather than the calculation itself. One function therefore copes with every kind of output you need.

One line per call

Each print call starts a new line. Once it has sent its item to the screen, the next output begins on the line below, so calls never run into each other, however many you write in a row.

Brackets with nothing between them, print(), output no characters but still move to the next line, leaving a blank line behind. You use it to space out output so it is easier to read.

Printing a pattern

Because each print call starts a fresh line, you can print a pattern, picture or table of characters row by row, using one print call for every row. The characters you place in the brackets appear exactly in that row, so you build the pattern from the top downwards and never need to type a line break yourself.

team_points = 31
print("Sports day results")   # first line of output
print()                        # empty brackets: a blank line
print("Points scored:")
print(team_points)
print(team_points + 9)

Output:

Sports day results

Points scored:
31
40

Five calls give five lines, and the empty call in the middle leaves a deliberate gap between the heading and the scores beneath it.

A string is text written inside quotation marks, such as 'Ready to launch'. It can hold letters, digits, spaces and punctuation, and everything between the marks is part of the string, so the space in 'Ready to launch' is stored exactly as you typed it.

The quotation marks are delimiters: they show the computer where the string starts and where it ends. They are not part of the text itself, so they are never printed. Only the characters inside them reach the screen.

# the quotation marks mark out the text but are not shown
print("Gallery opens at 10am")
print('Exhibition: Sculpture')

Output:

Gallery opens at 10am
Exhibition: Sculpture

Single or double quotation marks

You can wrap a string in either single or double quotation marks. print('Match postponed') and print("Match postponed") do exactly the same thing, so pick one style and keep to it.

What matters is that the two ends match: the string must open and close with the same type of mark. If you start with a double mark and finish with a single one, the computer looks for a closing " and never finds it, so the program stops with an error before anything is printed.

When you put something inside print(), Python works out the item first and then shows it as text. A number is shown as its value, an expression is calculated before anything appears, and characters in quotation marks are shown exactly as they were typed.

Numbers and expressions

A number can go straight into the brackets with no quotation marks, so print(27) shows 27. An expression without quotation marks is evaluated first: Python works it out and prints only the result. If a bus has 52 seats and 19 are taken, print(52 - 19) prints 33, never the sum itself. The same happens with multiplication, where print(8 * 7) prints 56.

Quotation marks stop the working out

Quotation marks turn the characters into a string, so nothing is calculated: print('52 - 19') prints 52 - 19. The brackets hold the item that print sends to the screen; the quotation marks mean that item is just characters.

Function calls inside print

A function call placed inside the brackets is run first, and the value it returns is what gets printed. len('basketball') returns 10, so print(len('basketball')) prints 10. Text handed to a function must be in quotation marks; without them Python reads the word as a variable name and the program stops with an error.

# A number, an expression, quoted text and a function call
print(27)
print(52 - 19)
print('52 - 19')
print(len('basketball'))

Output:

27
33
52 - 19
10

You can give print() several items at once by separating them with commas. Python prints all the items on the same line and adds a single space of its own between each pair. The commas are separators only, so they do not appear in the output.

This is handy when a line is made from separate pieces, such as a label, a team name and a score. Each comma tells Python that another item is coming.

home_team = "Hawks"
home_score = 4
away_team = "Wolves"
away_score = 1
print("Final score:", home_team, home_score, "versus", away_team, away_score)

Output:

Final score: Hawks 4 versus Wolves 1

The score variables hold numbers, but they do not need to be converted to strings first. When the items are separated by commas, print() displays each number as part of the line. It works through the items from left to right. It does not squash the items together with no gap, and it does not add several spaces: there is one space between neighbouring items.

Do not add extra spaces at the ends of the text items to separate them. The comma already supplies one space, so extra spaces would make the gap wider.

Concatenation means joining two or more strings end to end to make one longer string. In Python 3 you do it with the plus operator: put + between two strings and the result is one string holding the characters of the first followed by the characters of the second.

Joining strings with plus

You can join string literals, variables that hold strings, or a mixture of both, and you can chain as many pieces as you like in one expression. A quiz program might store a player's first name and surname separately, then join them into one name to display:

first_name = "Priya"
last_name = "Raman"
full_name = first_name + " " + last_name
print(full_name)

Output:

Priya Raman

Plus only glues the pieces together, so it adds nothing of its own. Any space you want must be typed inside one of the string literals, as the " " above does. Leave it out and the two words are squashed together into one, which looks wrong but is not an error, so the program still runs.

Joining a string and a number

Plus expects two strings, and it can also add two numbers, but it cannot do both jobs at once. Gluing a piece of text to a number therefore stops the program with an error:

team = "Falcons"
points = 42
print(team + points)

Output:

TypeError: can only concatenate str (not "int") to str (line 3)

Python will not guess which job you meant, so it refuses to run that line. Until you learn how to convert a number into a string, output the text and the number as separate items with a comma between them, which writes them on the same line with a single space in between. The number is printed as a value and needs no conversion.

To work out a program's output, follow the code one statement at a time, from top to bottom. For each statement, update the value of any variable it changes. When you reach a print() call, work out what it would show — quoted text as written, a variable's current value, or an expression calculated first — and note that down before moving on.

The order matters because a variable can hold one value early in a program and a different value later. A print() call never changes a variable, but an assignment such as boxes = boxes + 3 does. Keep a running record of every value so you never use an old one by mistake.

boxes = 6
boxes = boxes + 3
print("Boxes counted")
print(boxes)
boxes = boxes * 4
print(boxes - 5)

Output:

Boxes counted
9
31

Track values with a trace table

A trace table records the value of each variable, and any output, after every statement. That makes it clear which value each print call uses.

StatementValue of boxesOutput
Start6none
boxes = boxes + 39none
print("Boxes counted")9Boxes counted
print(boxes)99
boxes = boxes * 436none
print(boxes - 5)3631

At the print(boxes) call, boxes holds 9, so 9 appears on screen. The next assignment changes it to 36, so the last print call starts from 36, works out 36 - 5, and prints 31. Reading the print calls out of order, or skipping an assignment in between, gives the wrong output.

An output statement can look almost right and still stop your program dead. When Python meets a line it cannot make sense of, it stops with an error at that point, so the results that line should have printed never appear.

Three slips that stop the program

  • Unmatched quotation marks: a string must open and close with the same kind of quotation mark. print("Match over) opens a double-quoted string but never closes it, so Python keeps reading to the end of the line and fails.
  • Missing bracket: every opening bracket needs a closing partner. print("Kick off" starts the function call but never closes it, so Python reaches the end of the line still waiting for the bracket.
  • Incorrect capitalisation: Python treats capital and lower-case letters as different characters. PRINT is not the same name as print, so Python has nothing stored under it.

Text that isn't in quotation marks

Quotation marks are what tell Python to treat words as text. Leave them out and Python reads the word as a variable name, then looks for a stored value with that name. print(Full time) fails straight away because the space splits one name into two words. Even print(full_time) fails unless you have already assigned a value to full_time. Putting the quotation marks back prints the words themselves instead.

Here is a program carrying one of these slips. The string opens with a double quotation mark but there is no closing mark, so the string is never closed.

away_score = 3
home_score = 1
print("Away score: away_score, home_score)

Output:

SyntaxError: unterminated string literal (detected at line 3) (line 3)

With the closing mark in place, the corrected program runs and prints the labels and the values held in the variables.

away_score = 3
home_score = 1
print("Away score:", away_score, "Home score:", home_score)

Output:

Away score: 3 Home score: 1

Also useful