Python: The print Function

Python: The print Function

The print() function in Python is used to display information on the screen. It takes whatever you give it—whether it’s text, numbers, or even calculations—and shows it to the user. This is especially useful for interacting with the user or checking what’s happening inside your program.

One of the most common uses of print() is for debugging. If something in your program isn’t working as expected, you can use print() to show the values of variables or track the flow of the program to figure out where things might be going wrong. Whether you’re just starting or working on a complex project, print() is an essential tool for every Python programmer.

Basic Usage of print()

The simplest way to use the print() function is to display text. You just pass the text you want to show inside the parentheses, and Python will print it on the screen. The text needs to be inside quotes (single or double), as that tells Python it’s a string.

Here’s an example of printing a simple message:

print("Hello, world!")

When you run this code, Python will output:

Python: The print Function

This is the most basic use of print()—just showing a string to the user. You can print any text this way, whether it’s a greeting, a question, or even a more complex message.

Printing Multiple Values

You can print multiple values at once by separating them with commas inside the print() function. Python will automatically add spaces between each value when displaying them on the screen.

Here’s an example where we print a number and a string together using a name:

age = 30
name = "Edward"

print("Name:", name, "Age:", age)

The output will be:

Python: The print Function

In this example, the string "Name:", the variable name, the string "Age:", and the variable age are all printed together, with spaces automatically added between them. You can use this to display a mix of text and values in a single line.

Adding Newlines and Special Characters

By default, when you use print(), it adds a newline at the end of the output. This means each print() statement starts on a new line.

For example:

print("Hello!")
print("How are you?")

The output will be:

Python: The print Function

Python automatically moves to the next line after printing each statement.

Adding Special Characters

You can also include special characters like newline (\n), tab (\t), and others inside your strings to control how the output appears.

  • Newline (\n): Moves to the next line.
  • Tab (\t): Adds a tab space.

Here’s an example of using these special characters:

print("Hello!\nHow are you?")
print("Item1\tItem2\tItem3")

The output will be:

Python: The print Function

In the first print(), \n creates a new line between "Hello!" and "How are you?". In the second print(), \t adds a tab between "Item1", "Item2", and "Item3".

These special characters help you format your output in a way that makes it easier to read or visually structured.

Customizing the Separator Between Values

By default, Python separates values in the print() function with a space. However, you can change this separator using the sep parameter. The sep parameter lets you specify a custom string to place between each value you print.

For example, if you want to separate the values with a comma, you can do the following:

name = "Edward"
age = 30

print(name, age, sep=", ")

The output will be:

Python: The print Function

Here, the sep=", " parameter tells Python to place a comma followed by a space between name and age instead of the default space.

You can use any string as a separator. For example, to separate values with a dash (-), you can do:

print(name, age, sep="-")

The output will be:

Python: The print Function

This is useful when you want your output to have a specific format or structure.

Ending the Line with a Custom Character

By default, the print() function ends the output with a newline (\n), which means the next printed output starts on a new line. However, you can change this behavior using the end parameter. This lets you customize what is printed at the end of the line, such as a space, exclamation mark, or even no character at all.

Here’s an example where we end the print statement with a space instead of a newline:

print("Hello", end=" ")
print("Edward!")

In this case, the end=" " parameter adds a space at the end of the first print() statement, causing the second print() to continue on the same line.

You can also use other characters like exclamation marks:

print("Hello", end="!!! ")

print("How are you?")

This gives you flexibility in how your output is formatted, allowing you to control the flow of your printed text more precisely.

Printing Variables and Expressions

You can use the print() function to display not just simple text, but also variables, calculations, and expressions. This allows you to show the results of operations or display dynamic values in your program.

Printing Variables

You can print the value of a variable directly by passing it to print():

name = "Lucia"

print(name)

Printing Calculations

You can also print the result of a calculation or arithmetic operation. For example:

x = 10
y = 5

print(x + y)

In this example, x + y is evaluated first, and then the result (15) is printed.

Printing More Complex Expressions

You can print more complex expressions, such as string concatenations, conditional statements, or even mathematical expressions combined with text:

price = 50
discount = 10

print("Discounted price is:", price - discount)

This shows how you can display the result of a calculation alongside some descriptive text, making your output more meaningful and informative.

Using f-Strings for String Interpolation

In Python, f-strings (formatted string literals) provide a simple and readable way to embed variables directly inside a string. You can use f-strings by prefixing the string with the letter f and placing variables or expressions inside curly braces {}.

This method allows you to create more dynamic and readable strings without having to use concatenation or str.format().

Example: Printing a message with a variable using f-strings

Here’s an example of using an f-string to print a message with a variable:

name = "Stephen"
age = 28

print(f"Name: {name}, Age: {age}")

In this example, {name} and {age} are replaced with the values of the respective variables, resulting in a clean and readable output.

More Complex Expressions Inside f-Strings

You can also include expressions inside f-strings. For instance, performing a calculation within the string:

x = 5
y = 10

print(f"The sum of {x} and {y} is {x + y}.")

f-strings are powerful because they allow you to mix both static text and dynamic values seamlessly, making your code cleaner and easier to read.

Printing in Different Data Formats

You can use format() or f-strings to print values in different formats, such as integers, floats, and strings, and even control how those values are displayed. This is especially useful for controlling the appearance of numbers (like specifying the number of decimal places) or formatting strings.

Using format() Method

With the format() method, you can specify the format of a value by using placeholders in the string. For example, to print a float with two decimal places, you can do:

pi = 3.14159

print("Pi to two decimal places: {:.2f}".format(pi))

Here, {:.2f} means you want to display the number as a float with exactly two digits after the decimal point.

Using f-Strings for Formatting

f-strings also support formatting in a similar way, making it more readable. Here’s the same example using an f-string:

pi = 3.14159

print(f"Pi to two decimal places: {pi:.2f}")

Formatting Integers

If you want to format integers, you can also specify how they should be displayed. For example, to display an integer as a padded number:

num = 42

print(f"Number with leading zeros: {num:05}")

In this example, {num:05} pads the number with leading zeros to make the total length of the number 5 digits.

Printing Percentages

You can also format percentages. For example, to print a percentage value with one decimal point:

percentage = 0.876

print(f"Percentage: {percentage:.1%}")

The output will be:

Python: The print Function

This shows how to use format() or f-strings to print values in different formats, making your output more customizable and readable.

Conclusion

In this article, we covered the essentials of Python’s print() function. Here’s a quick recap of the key points:

  • Basic usage: How to display text and variables using print().
  • Printing multiple values: How to print multiple values at once, separated by spaces or custom separators.
  • Customizing output: Using end and sep parameters to control how printed values are separated or ended.
  • Adding newlines and special characters: How to format your output with newlines (\n), tabs (\t), and other special characters.
  • String interpolation: Using f-strings to easily insert variables or expressions into strings.
  • Formatting values: How to format different types of data, like integers, floats, and percentages, for better readability.

With these tools, you can better control your output and make your Python programs more interactive and user-friendly.

Scroll to Top