How to print variables in Python. Python, with its simplicity and versatility, has emerged as a favorite among both beginners and experienced programmers. One of the fundamental tasks you will frequently encounter in Python is printing variables. Whether you are debugging the code or displaying results. This tutorial will guide you through the various methods of printing variables in Python.
Table of Contents
The Print Function
The most straightforward way to print a variable in Python is by using the print()
function. This built-in function outputs the value of a variable to the console, making it an invaluable tool for displaying program results or debugging. Here is how you can use it:
var = "Hello, Learners"
print(var)
Printing Text with Variables in Python
Often, You will want to print a variable along with some text to make the output more understandable. Python offers several ways to achieve this, each with its advantages.
String Concatenation
You can concatenate strings and variables in Python using the '+'
operator, Ensuring that the variable is a string.
name = "John"
print("Hello, " + name )
String Formatting in Python
Python provides several string formatting techniques, offering flexibility in how you inject variables into Strings.
Using the ‘%’ Operator
name = "Tom"
print("Hello, %s " % name )
Using format() Method
name = "Harry"
print("Hello, {} ".format(name))
f-strings in Python
This modern approach allows you to embed expressions inside String literals using curly braces {}
.
greeting = "Good Morning!!"
print(f"Hello, {greeting}")
Printing Multiple Variables
To print multiple variables separated by space in Python, Simply pass them as separate arguments to the print()
function.
var1 = "Python"
var2 = "Print"
print(var1,var2)
Advanced Printing Techniques in Python
Python’s print()
function also supports keyword arguments that can enhance your output. For instance, you can use the 'sep'
argument to change the default separator between items from space to something else.
var1 = "Python"
var2 = "Print"
print(var1,var2, sep = "::")
Similarly, the 'end'
argument lets you decide what is printed at the end of the output, Overriding the default newline character.
print ("Hello",end=", " )
print("Learners")
Happy Coding & Learning
1 thought on “Printing Variables in Python”