liveBook · Manning

Print

As explained in Learn AI-Assisted Python Programming, Second Edition

A print statement is a language construct that writes a value or text representation to an output stream.

print is Python’s built-in way to output a message or value to the screen. It is the output counterpart to input, which receives information from the keyboard. section 4.3.1

Use print to:

  • Show text or computed values, such as a greeting or the area of a square. section 2.6.1
  • Inspect variable values while debugging, placing statements at useful points in a function or loop. section 8.2.1
  • Trace which values cause an incorrect result, such as identifying every word counted by a matching loop. section 8.2.1

Finding an overcount

A word-counting function that checks whether "dan" appears anywhere counts both "Dan" and "danger". Add print(word, "is being counted") inside the if statement, rerun the test, and inspect the output. The trace reveals which word causes the unexpected count, helping guide a correction that counts only the exact word "Dan". section 8.2.1

Listing 8.2 Example of a print statement to find the bug
def count_words(words):
    count = 0
    for word in words:
        if "dan" in word.lower():
            print(word,"is being counted")    #1
            count += 1
    return count

View the debugging listing that places print at the point where the counter changes. section 8.2.1

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains calls, arguments, Python 3 parentheses, and strategic placement for tracing values, but not output-stream internals.
Examples
Demonstrates greetings, calculated square areas, and tracing words incorrectly counted by a loop.
What it assumes
Assumes basic Python expressions, variables, functions, loops, and conditionals while introducing print as a built-in function.
What you can do after
Diagnose logical errors by printing values and messages at selected execution points.
How it connects
Connects print with input, variables, functions, loops, logical errors, testing, and debugging.

Also explained in

Compare how 5 books explain print →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.