Knowledge for the World

How to print in Python


Python comes with a built in print function. However, prior to Python 3 this function is generally not available as a normal function call. Rather it is a statement. Print is called like this: print "hello world" In Python 3, print is called as a typical function: print("hello world") The print function takes multiple expressions and converts them to a string. Print automatically formats the output by putting a space between each expression and a newline at the end. print "The answer to 3 + 4 is", 3 + 4, 3 + 4 == 7 will print: The answer to 3 + 4 is 7 True


The sys module in python provides a method for writing directly to stdout (standard out). The print function is basically a wrapper for this function and provides formatting discussed in the previous step. You can write directly to stdout like this: import sys sys.stdout.write("hello world") You will see that this output differs from print in that it includes no newline at the end. To imitate the print function you can write: import sys sys.stdout.write("hello world\n")