How To Print Variables In Python

In this tutorial, we will learn how to print variables in Python. Variables are a crucial part of any programming language, and they are used to store different types of data. Printing variables allows you to view the contents of a variable, which can be helpful for understanding your code and debugging.

Let’s dive in and learn how to print variables in Python through a simple step-by-step process.

Step 1: Create a Variable

To print a variable, you need to create one first. Variables in Python can store different types of data, such as integers, floats, strings, and more. Here’s an example of creating a string variable:

In this example, a variable named name is assigned the value "John Doe".

Step 2: Use the print() Function

The next step is to use the print() function to print the contents of the variable. This function takes one or more arguments and prints them on the screen. Here’s the line of code that prints the name variable:

When executed, this line of code will display the following output:

John Doe

Step 3: Combine Strings and Variables

In some cases, you may want to print a combination of strings and variables in a single line. You can do this using the string formatting method. Let’s see a couple of examples below:

Using f-strings (Python 3.6+):

Using str.format():

Both of these methods will produce the same output:

John Doe is 25 years old.

Using f-strings is the more modern and preferred way, as it makes the code more readable.

Full Code Example

Here’s the full code example from the steps above:

This code, when executed, will produce the following output:

John Doe
John Doe is 25 years old.

Conclusion

Now you know how to print variables in Python. By using the print() function and string formatting techniques, you can easily display the contents of a variable, as well as a combination of strings and variables.