The Python print() function prints a given object to the standard output. It is possible to pass multiple objects to print().
The standard behaviour of the print() function is to print to screen, to change this behaviour the file argument is used. It is possible to save the output to a file instead of the screen.
print hello world
The first program users write while learning a new programming language, is one that just prints hello world to the screen. To achieve this in Python we use the print() function.
# print hello world
The input is in this case a string and it is printed to the screen by Python.
print multiple strings
It is also possible to combine two or more strings.
# concatenate strings and print
myString1 = "hello"
myString2 = "world"
myString3 = "!"
print(myString1 + myString2 + myString3)
Python concatenates all strings connected via the plus operator and print() returns the combined string.
It is also possible to combine string with variable content.
# concatenate variable and string
myString1 = 'hello'
print(myString1 + ' world!')
The variable myString1 is now concatenated with the string and printed.
print integers, float and other types
To print() other types than strings, we need to convert them to strings first. This is necessary even for integers and float values. Use the str() function() to convert other types to strings.
# convert float & integer to string and print
myFloat = 2.55
myInt = 5
print("my numbers are:" + str(myFloat) + " and " + str(myInt))
The float and integer values are converted to strings and printed.
my numbers are: 2.55 and 5
print() can print float and integers, but the concatenation with string requires that all parts are string types. If that's not the case a TypeError exception is raised.
TypeError: unsupported operand type(s) for +: 'float' and 'str'
The syntax of the print() function is:
print(objects, seperator=' ', end='\n', file=sys.stdout, flush=False)
The print() function accepts between 1 and 5 arguments:
required: objects, the objects to print.
optional: seperator, the seperator between objects. Default is a space ' '
optional: end, the end of line. Default is a new line '\n'
optional: file, the object to write to. Default is sys.stdout = print to screen.
optional: flush, the stream is flushed. Default is False
print() return values
The print() function returns None. The output is printed to the screen or saved in a file, specified in the file argument.