How To Use Print In Python

Python is a versatile programming language widely used across different fields like web development, data analysis, machine learning, and more.

One of the most essential and frequent programming tasks is displaying text and values on a computer screen. That is where the print() function comes in. In this tutorial, we will look at how to use the print() function in Python, as well as some examples of its use.

Step 1: Understanding the print() function

The print( ) function in Python is used to display/output data on the screen. By default, print() outputs to the console/terminal, and it can also write to a file if desired.

When you run this code, the output will be:

Hello, World!

Step 2: Printing multiple arguments

With the print() function, you can print multiple arguments separated by commas. The values are separated by a space by default.

The output will be:

Hello, World!

Step 3: Changing the separator and using the end parameter

The sep and end parameters can be used to change the default behavior of the print() function. By default, sep is set to a single space, and end is set to a newline character.

The output will be:

Hello-World!.

Step 4: Printing formatted strings

Formatted strings, also known as f-strings, provide a convenient way to embed expressions and variables inside string literals. To use f-strings, add an “f” or “F” before the string and enclose expressions within curly braces {}.

The output will be:

My name is John and I am 30 years old.

Step 5: Printing to a file

The file parameter in the print() function can be used to direct the output to a file instead of the console. To write the output to a file, you need to open it with the ‘w’ (write) or ‘a’ (append) mode. Don’t forget to close the file after writing to it.

This code will create an “output.txt” file with the text:

Hello, World!

Full Code:

Conclusion

In this tutorial, we have gone over the basics of using the print() function in Python, including how to display/output data on the screen, print multiple arguments, change the default separator, use formatted strings, and print contents to a file.

Mastering the print() function is essential for displaying data and debugging your Python code, so keep practicing to get more comfortable with it.