How To Output A Message In Python

Python is a versatile and powerful programming language that is easy to learn and widely used across various industries. One of the most basic tasks that you need to know when starting with Python is how to output a message.

This helps in displaying the result of your code or a simple text message. In this tutorial, we will explore different ways to output messages in Python by using the print() function.

Step 1: Using the print() Function

The simplest way to output a message in Python is by using the print() function. The print() function writes a string to the console, followed by a newline character unless specified otherwise. To use the print() function, you just need to call it with the text that you want to display. You can specify the text by placing it between quotes (” or “”) inside the print() function.

This simple line of code will output the following:

Hello, World!

Step 2: Printing Multiple Messages

You can output multiple messages using the print() function by separating the messages with a comma. This will output the messages separated by a space.

The output will look like this:

Hello, World!

Step 3: Formatting the Output

To get more control over the output format, you can use the formatted string literals or f-strings. They allow you to embed expressions inside the string literals, which are enclosed in curly braces {}. The expressions inside the curly braces are evaluated at runtime and then formatted and inserted into the resulting string using the format string syntax.

The output will be:

My name is John and I am 30 years old.

Step 4: Suppressing the Newline Character

By default, the print() function adds a new line character at the end of the output. If you want to suppress the newline character, you can use the end parameter.

The output will be:

Hello, World! I am learning Python.

Step 5: Redirecting the Output to a File

In some cases, you might want to redirect the output of the print() function to a file instead of displaying it on the screen. You can do this by using the file parameter.

The output will be written to the file output.txt

Full Code


In this tutorial, we have covered various ways to output messages in Python using the print() function.

From basic string output to formatted strings and redirecting output to a file, you now have the knowledge needed to effectively communicate with users through your Python programs. Keep exploring the wide range of features Python has to offer and happy coding!