Python print() function

Python print() function basically prints the given input or object to the output screen or the corresponding stream file.

Syntax:

print(objects, sep=value, end=end_value, file, flush)

Python print() function Arguments:

ArgumentsDescriptionRequired/Optional
object(s)An object or input stringRequired
sep=’valueSpecification on how the objects are to be separated.
Default separator value is ‘ ‘
Optional
end=’end_value’Specifies what is to be printed at the end.
Default value is ‘\n’
Optional
fileIt is an object with a write method. Default value is sys.stdout.Optional
flushIt is a boolean value that specifies whether the output obtained is flushed (True) or buffered (False). Default value is False.Optional

1. Basic understanding of Python print() function

# Passing a single object
print("Engineering Discipline") 
  

Output:

Engineering Discipline

2. Printing of multiple objects with Python print() function

input = "Safa"

print("Result is: ", input) # Contains two objects

Output:

Result is:  Safa

3. Printing a Tuple and a List with Python print() function

Python print() function can be used to print Strings, Tuples, Lists, etc. to the output screen.

input_tuple = ("YES", "NO", 200) # Tuple
print(input_tuple)

input_list = [10,'Apple', 20,'Football', 70] # List
print(input_list) 

Output:

('YES', 'NO', 200)
[10, 'Apple', 20, 'Football', 70]

4. Python print() function with “sep” keyword

By default, as you all must have observed, the values in the output are separated by space. But, now the User can customize it by replacing the default value i.e. ‘ ‘ (space) using any symbol or value.

value1 = int(10)


value2 = 'Social Science'


print(value1, value2, sep='+')


Output:

10+Social Science

5. Python print() function with “end” keyword

As observed, the default value of the ‘end’ parameter is ‘\n’ i.e. the Python print() functions ends with a newline (‘\n’).

But, now the User can customize it by replacing the default value i.e. ‘\n'(newline) using any symbol or value.

my_list = [10, 20, 0, 32, 56, 78, 90]


print('Printing the list..... ')
for x in my_list:
    print(x, end='$')


Output:

Printing the list..... 
10$20$0$32$56$78$90$

6. Python print() function with “file” keyword

Python print() function’s file parameter enables user to write to a file. If the mentioned file doesn’t exist, it creates a new file with the specified name and writes the output to it.

input_file = open('Print_function.txt','w')
print('Social Science', file = input_file)
input_file.close()

Output:

Print Function
print() Function

Conclusion

Thus, in this article, we have understood the working of Python’s print() function.


References