liveBook · Manning

Print

As explained in Get Programming: Learn to code with Python

A print statement is a language construct that sends specified values to a program's output stream.

Use Python’s print() command when you want a program to show a value or message to someone. In an IPython console, typing 3 + 2 lets you peek at its value; typing print(3 + 2) displays 5 as program output, without the console’s Out[] label. section 3.2

Print a value

Try print(13 - 1). Python evaluates 13 - 1 first, then prints 12. You can also print text with print("hello!"). The value inside the parentheses does not have to be a string. section 11.1

To print several values at once, separate them with commas: print(1, "/", 2, "=", 0.5) displays 1 / 2 = 0.5. Python adds spaces between those values. If you need 1/2=0.5 instead, convert the values to strings and join them before printing. section 11.1

Listing 11.2. Printing multiple objects
a = 1                                         #1
b = 2                                         #1
c = a/b                                       #2
print(a,"/",b,"=",c)                          #3

add = str(a)+"/"+str(b)+"="+str(c)            #4
print(add)                                    #5

Compare the comma-separated print call with the string built using str() and +. Both show the division result, but only the first adds spaces automatically. section 11.1

In a longer program, print can label calculated results—such as Hours and Minutes—or tell a player which commands a game accepts. Quick check: what appears when you run print(0), and how is that different from typing 0 alone in the IPython console? section 6.2 section 15.1 section 3.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains evaluated expressions, mixed-type arguments, automatic spaces, and string concatenation; does not detail output-stream internals.
Examples
Uses arithmetic and strings, a formatted division result, labeled conversion output, and game instructions.
What it assumes
Starts with console arithmetic and introduces expressions before using variables and strings in print calls.
What you can do after
Build it from scratch: display calculated results and labeled output in a small Python program.
How it connects
Connects print to expressions, variables, string concatenation, and input().

Also explained in

Compare how 5 books explain print →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.