Python print() Function

Prints the message on the screen

Usage

The print() function prints the specified message to the screen or the text file.

The message can be a string, or any other object (such as number, list, tuple etc.)

Syntax

print(objects,sep,end,file,flush)

Python print() function parameters
ParameterConditionDescription
objectsOptionalZero or more objects to print.
sepOptionalA string to print between each object.
Default is a single space ‘ ‘
endOptionalA string to print at the end.
Default is a newline ‘\n’.
fileOptionalAn object with a write(string) method.
Default is sys.stdout (screen)
flushOptionalIf True, output buffer is forcibly flushed

sep, end, file and flush must be specified as keyword arguments.

For example, sep = '-' or end = ' '

Basic Example

Example: Print the message on the screen

print('Hello, World!')

Output:

Hello, World!

You can print as many values as you like, just separate them with a comma ,.

Example:

print('One','two','three','four','five')

Output:

One two three four five

Separator Parameter

When you print multiple values, each value is separated by a space ' '.

By specifying sep parameter, you can separate each value by something other than a space.

Example: Separate each value with ‘…’

print('One','two','three', sep='...')

Output:

One...two...three

End Parameter

The print() function includes a newline at the end by default.

To print the values without a trailing newline, specify end parameter.

Example: Print without newline

print('First line.', end=' ')
print('Next line')

Output:

First line. Next line

If no values are specified, print() will just print end parameter.

File Parameter

The print() function prints the values to the screen by default.

However, you can print them to the file by specifying the file parameter.

Example: Write a file with print() function

with open('myfile.txt', 'w') as f:
    print('Hello, World!', file=f)

You can print any object other than string such as number, list, tuple etc.

The object is converted into a string before written to the screen.

Example:

# Print a list
print(['red', 'green', 'blue'])

# Print a tuple
print((1, 2, 3))

Output:

['red', 'green', 'blue']
(1, 2, 3)