What is the Python print() Function?

The Python print() is a built-in function that allows you to display output or information on the screen or in the terminal. It’s a fundamental tool for interacting with users and for debugging purposes. By using the print() function, you can showcase data, variables, and other content to provide insights and communicate within your Python programs.

For better understanding imagine you’re at a grand event, and you’re eager to make an announcement to captivate the audience’s attention. The print() function in Python serves a similar purpose: it allows you to display messages, values, and expressions on your screen. Think of it as your communication tool to convey information from your code to the user.

With a solid understanding of the basics of Python print(), you’re ready to unlock its practical applications. Proficiency in its syntax and parameters is key, as they form the basis for working with the function’s examples. Mastering these aspects empowers you to harness the function’s potential across various scenarios efficiently.

Python print() Syntax and Parameters

To use the print() function, all you need is the keyword print followed by a pair of parentheses. Within the parentheses, you can include the content you want to display, Let’s explore this:

print(message)

Imagine you’re a chef creating a masterpiece dish. The print() function becomes your plating tool, allowing you to present your output in a way that’s aesthetically pleasing and easily digestible. While the basic syntax involves a single parameter (the content you want to display), Python print() function offers additional parameters to enhance your output:

I. Sep

This parameter specifies the separator between multiple items you want to print. By default, it’s a space.

II. End

This parameter defines what should be printed at the end of your output. The default is a newline character (\n).

Now that you have a good grasp of the syntax and parameters of Python print(), let’s delve into its return values to gain insight into how this function operates in real-world examples.

Python print() Return Value

Imagine you’re a treasure hunter, and the print() function is your map to uncovering hidden riches. While the primary purpose of print() is to display output, it also holds a subtle secret: its return value. Contrary to some expectations, the print() function doesn’t return the printed content itself. Instead, it returns None, indicating that it doesn’t produce a tangible result. Let’s illuminate this concept with an example.

Example Code
output = print("Hello, explorers!") print("Return value:", output)

Here, we’re exploring the behavior of the print() function. We start by using the print() function to display the message Hello, explorers! on the screen. This message serves as an informal greeting to our fellow programmers. Next ,we’ve assigned the result of the print() function to the variable named output. This might seem a bit unusual, as we’re used to printing directly without capturing the return value. But here, we’re investigating what happens when we store the result of the print() function.

Afterward, we use another print() function to display the value of output. We’re curious to see what’s stored in this variable after using the print() function. You might expect it to be None, which is a special value in Python indicating the absence of a meaningful result. In this expedition, the first print() function displays the greeting, and the second print() function showcases the return value, which is None.

Output
Hello, explorers!
Return value: None

This showcases that while the print() function performs its intended task of displaying output, its return value is typically not utilized in this context.

I. Creation of the print() Object

Creation of Python print() object refers to the concept of capturing the output of the print() function and storing it in a variable.  When you create a print() object, you’re essentially using the print() function in a way that allows you to both display output and retain the value that the function returns. This can be helpful in certain scenarios where you want to keep track of the output or manipulate it before displaying it. For example:

Example Code
output_object = print("Welcome To Python Helper!") print("Output object:", output_object)

In this example, the print() function is used to display the message Welcome To Python Helper! on the screen. However, the interesting part is that the return value of the print() function (which is None) is stored in the output_object variable. Later, when we print the value of output_object, it will show None. The creation of the print() object isn’t a common practice since the primary use of the print() function is to directly display output.

Output
Welcome To Python Helper!
Output object: None

However, The above example showcases the dual nature of the print() function – both as a display mechanism and as a function that returns a value.

II. Displaying Variables Using the print()

Displaying variables using Python print() is a fundamental way to showcase the values stored in variables on the screen. This process involves using the print() function to output the content of variables so that you can see their values and work with them during program execution. For example.

Example Code
distance_london_to_america = 3620 unit = "miles" print("The distance from London to America is:", distance_london_to_america, unit)

For this example, we’ve defined a variable named distance_london_to_america and set it to 3620, representing the distance in miles from London to America. Another variable called unit holds the string miles, indicating the unit of measurement we’re using.

The print() function is then used to display a message that combines the distance, the text The distance from London to America is:, the value stored in the distance_london_to_america variable, and the value of the unit variable.

Output
The distance from London to America is: 3620 miles

In this narrative of numeric exploration, the print() function amplifies your variable’s value for all to hear.

III. Python print() with String

In Python, the print() function with a string as its argument is used to display the content of the string on the standard output, which is usually the console or terminal. This allows you to show text, messages, variables, or any other information to the user or developer during the execution of a program. For instance:

Example Code
message = "Hello, Python Explorer!" print(message)

Here, we have a variable named message which holds the string Hello, Python Explorer!. When we use the print() function with the message variable as an argument, it displays the content of the string on the screen. So, when we run the code, it will output the text on the screen.

Output
Hello, Python Explorer!

This is a simple way to showcase a message or information in Python programming.

IV. Formatting Output with print()

Formatting output with the print() function allows you to control the way your data is presented. It enables you to structure your output by incorporating variables, text, and special formatting options to create a more organized and visually appealing display. This ensures that the information you’re conveying is not only accurate but also easily comprehensible to both developers and end-users. Consider below illustration.

Example Code
temperature_celsius_london = 27.5 temperature_celsius_new_york = 18.2 temperature_fahrenheit_london = (temperature_celsius_london * 9/5) + 32 temperature_fahrenheit_new_york = (temperature_celsius_new_york * 9/5) + 32 print("Current temperature in London:", temperature_celsius_london, "°C") print("Temperature in London:", temperature_fahrenheit_london, "°F") print("\nCurrent temperature in New York:", temperature_celsius_new_york, "°C") print("Temperature in New York:", temperature_fahrenheit_new_york, "°F")

In this example, we’ve included temperatures for both London and New York in Celsius. We then converted these temperatures to Fahrenheit using the formula (Celsius * 9/5) + 32. Finally, we displayed the temperatures in both Celsius and Fahrenheit using the print() function.

Output
Current temperature in London: 27.5 °C
Temperature in London: 81.5 °F

Current temperature in New York: 18.2 °C
Temperature in New York: 64.75999999999999 °F

In this visual presentation of temperature, the print() function helps you arrange the output to be clear and visually appealing.

V. Python end in print()

Imagine you’re a composer writing a musical masterpiece. The end parameter in Python print() becomes your baton, allowing you to evaluate what should appear at the end of each printed statement. By default, the end parameter is set to a newline character (\n), which means that each call to print() creates a new line after the output.

However, with the end parameter, you can control this behavior and shape your output according to your creative vision. Let’s explore this with an example:

Example Code
print("One", end="-") print("Two", end="-") print("Three", end="!")

For this example, we’re using the print() function to display text, but with a twist in how the output is formatted. Instead of the default behavior where each print() statement adds a newline at the end, we’re modifying it using the end parameter.

We start by printing the text One and setting the end parameter to “-“. This means that after One is printed, instead of adding a newline, a hyphen (“-“) is added. So, the next print() statement, which prints Two, appears right after One with a hyphen in between. We continue this pattern for Three, but this time we set the end parameter to “!“. This means that after Three is printed, an exclamation mark (“!“) is added instead of a newline.

Output
One-Two-Three!

In this symphony of output, the end parameter dictates that hyphens and an exclamation mark should connect the statements, creating a unique output style.

VI. Controlling Separators in the print()

Controlling separators wiht Python print() allows you to evaluate how different elements are separated when they are displayed. By default, when you use multiple arguments in the print() function, they are separated by a space and followed by a newline character. However, there are scenarios where you might want to customize the separator between these elements, or even specify that no separator should be used.

By utilizing the sep parameter of the print() function, you can control the separator between the elements being printed. This parameter lets you specify a custom string that will be used as the separator between each argument in the print() function. Here’s an example of using the print() function to create a to-do list with custom separators:

Example Code
print("Welcome to my To-Do List:\n") task1 = "Buy groceries" task2 = "Clean the house" task3 = "Go for a walk" print(task1, task2, task3, sep=" | ")

Here, we have created a to-do list with three tasks. Each task is represented by a separate string variable: task1, task2, and task3. The tasks are defined as Buy groceries, Clean the house, and Go for a walk.

Now, here comes the interesting part. We want to display these tasks using the print() function, but we want to separate them with a custom separator instead of the default space. To achieve this, we use the sep parameter within the print() function.

We pass the task1, task2, and task3 variables as arguments to the print() function. Along with these arguments, we include the sep parameter and set it to ” | “. This means that when the print() function displays the tasks, it will use the ” | ” separator between them.

Output
Welcome to my To-Do List:

Buy groceries | Clean the house | Go for a walk

As you can see, the tasks are printed one after the other, and the custom separator ” | ” is used to neatly separate them, giving the appearance of a structured to-do list. This approach allows you to control how the tasks are displayed and presented to the user.

Python print() Advanced Examples

In the following section, we will examine several advanced examples of Python print() function, highlighting its flexibility and wide range of applications.

I. Python print() with User-Input

Using Python print() function with user input allows you to create interactive programs that prompt users for information and display their responses. This combination of input and output is essential for creating engaging and dynamic applications.

When you use the input() function to gather input from the user, you can use the print() function to display messages or results based on that input. This interaction enables you to create programs that take user preferences, data, or choices into account and provide meaningful output.

Example Code
name = input("What's your name? ") print("Hello,", name, "Welcome to our program!") age = input("How old are you? ") if int(age) >= 18: print("You're an adult!") else: print("You're still a minor.")

In this example, we’re creating an interactive program that gathers information from the user and responds with personalized messages based on their input.

First, we use the input() function to prompt the user with the question What's your name? The user’s response is then stored in the variable name. Next, we use the print() function to greet the user by displaying Hello, followed by their name and Welcome to our program! This creates a friendly and welcoming message tailored to the user’s name.

Moving on, we use the input() function again, this time asking How old are you? The user’s age input is stored as a string in the variable age. To determine whether the user is an adult or a minor, we convert the age string to an integer using int(age). We then use a conditional statement (if-else) to check if the user’s age is greater than or equal to 18. If the condition is met, the program prints You're an adult! Otherwise, it prints You're still a minor.

Output
What’s your name? Harry
Hello, Harry Welcome to our program!
How old are you? 20
You’re an adult!

By incorporating user input and conditional statements, this code creates an interactive experience, making the program’s output personalized and relevant to the user’s provided information.

II. Python print() to a File

In Python, the print() function can be used to write content to a file in addition on the screen output. By default, the print() function displays its content on the screen, but you can redirect this output to a file by specifying the file parameter.

When you use the print() function with the file parameter and provide the name of an open file object, the content will be written to that file instead of being displayed on the screen. This is useful for creating log files, generating reports, or saving program output for later analysis. Here’s an example of how the print() function can be used to write to a file:

Example Code
with open("output.txt", "w") as file: print("This is a line of text.", file=file) print("This is another line.", file=file) print("Succesfuuly print the line in the file")

Here, we start by opening the output.txt file in write mode using the open() function. The “w” mode indicates that we want to write to the file. By using the with statement, we ensure that the file will be properly closed after we finish using it. Within the with block, we use the print() function to write the text This is a line of text. to the file. The file parameter in the print() function specifies that we want to write to the output.txt file. This line serves as the first entry in the file.

Continuing inside the with block, we use the print() function again, once more targeting the output.txt file with the file parameter. This time, we write the text This is another line. to the file. This text becomes the second line in the file. As we exit the with block, the file is automatically closed for us, ensuring proper management of system resources.

To conclude, we print the message Successfully print the line in the file to the screen. This confirmation indicates that our task of writing lines to the file has been accomplished. Upon examining the contents of the output.txt file, we will find that it contains the following content. Below the output which show on your screen

Output
Succesfuuly print the line in the file

And underneath the displayed lines within your file.

Output
This is a line of text.
This is another line.

Through this code, you have efficiently utilized the print() function to write lines of text to the output.txt file, achieving the desired outcome.

III. Python print() with List

Python’s print() function makes it convenient to showcase the contents of a list in a well-organized and comprehensible format. This function simplifies the process of displaying individual elements within a list. As you print a list, each element within it is automatically separated by spaces and enveloped by square brackets. For a clearer understanding, let’s explore an example:

Example Code
class PrimeNumberGenerator: def __init__(self, limit): self.limit = limit self.primes = self.generate_primes() def is_prime(self, num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def generate_primes(self): primes = [] for num in range(2, self.limit + 1): if self.is_prime(num): primes.append(num) return primes prime_gen = PrimeNumberGenerator(50) print("List of prime numbers:", prime_gen.primes)

For this example, we have a PrimeNumberGenerator class that takes a limit as input and generates prime numbers up to that limit. The is_prime() method checks whether a number is prime, and the generate_primes() method populates a list with prime numbers within the specified limit.

We then create an instance of the PrimeNumberGenerator class with a limit of 50 using prime_gen = PrimeNumberGenerator(50). Finally, we use the print() function to display the list of prime numbers generated by the instance: print(“List of prime numbers:", prime_gen.primes).

Output
List of prime numbers: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

In this colorful showcase of information, the print() function and a list create a visually appealing representation of your data.

IV. Python print() with Dictionary

Imagine you’re a curator of a museum, and your dictionary is a gallery of exhibits. The print() function becomes your tour guide, leading your audience through the captivating world of key-value pairs. By incorporating a dictionary into the print() function, you can present data in a structured and meaningful way. Let’s venture into an example to see this in action.

Example Code
class CityTourGuide: def __init__(self): self.attractions = { "Eiffel Tower": "A famous iron tower located in Paris, France.", "Statue of Liberty": "A colossal neoclassical sculpture on Liberty Island, New York Harbor.", "Taj Mahal": "An iconic white marble mausoleum in Agra, India.", "Great Wall of China": "A series of fortifications made of stone, brick, tamped earth, and other materials.", "Pyramids of Giza": "Ancient pyramid complexes located in Egypt." } def provide_attraction_info(self, attraction): if attraction in self.attractions: info = self.attractions[attraction] print(f"{attraction}: {info}") else: print(f"\nSorry, information about {attraction} is not available.") tour_guide = CityTourGuide() print("Welcome to the City Tour!") print("\nAvailable attractions:") for attraction in tour_guide.attractions: print(f"- {attraction}") chosen_attraction = input("\nWhich attraction would you like to learn more about? ") tour_guide.provide_attraction_info(chosen_attraction)

Here, we have a CityTourGuide class that contains a dictionary called attractions. Each key in the dictionary represents an attraction, and its corresponding value provides a brief description of the attraction.

The provide_attraction_info() method takes an attraction as input and prints out its information if it’s available in the dictionary. The tour guide provides a list of available attractions and asks the user to choose an attraction they’d like to learn more about. The chosen attraction is then passed to the provide_attraction_info() method to display its information using the print() function.

Output
Welcome to the City Tour!

Available attractions:
– Eiffel Tower
– Statue of Liberty
– Taj Mahal
– Great Wall of China
– Pyramids of Giza

Which attraction would you like to learn more about? Taj Mahal
Taj Mahal: An iconic white marble mausoleum in Agra, India.

In this way, the tour guide uses the print() function to present information about different attractions, enhancing the tourist’s experience during the city tour.

V. Handling Exceptions and Errors with print()

Handling exceptions and errors with the print() function involves implementing strategies to manage and communicate errors that may occur while printing information. Python print() function is commonly used to display output, but errors can arise if the data being printed is not formatted correctly or if there are unexpected issues during the printing process.

By incorporating error-handling techniques, you can ensure that your program gracefully handles errors and provides meaningful feedback to users. This helps in identifying the source of errors and improving the overall user experience. For example, let’s consider a scenario where you want to print the result of a division operation, but you need to handle the case when division by zero occurs:

Example Code
numerator = 10 denominator = 0 try: result = numerator / denominator print("Result:", result) except ZeroDivisionError: print("Error: Division by zero is not allowed.")

In this example, we’re attempting to divide the numerator by the denominator, but since the denominator is zero, a ZeroDivisionError occurs. In order to manage this error, we employ a try-except construct. If a ZeroDivisionError occurs, the except block is executed, and an appropriate error message is printed.

Output
Error: Division by zero is not allowed.

By using error-handling techniques with the print() function, you can create more robust and user-friendly programs that handle unexpected situations gracefully and provide clear feedback to users when errors occur.

Now that you’ve comprehensively grasped the Python print() function, its uses, and its convenience and flexibility across various scenarios, you’ve established a strong foundation. To enrich your comprehension, let’s explore certain theoretical concepts that will greatly benefit you on your path through Python programming.

Print() work in Python 2

Now you’ve had the chance to explore the features and abilities of the Python print() function. Keep in mind that the print() function is not present in Python 2; it was introduced in Python 3. In Python 2, you use a different method to achieve printing. Here’s a way to grasp this distinction:

print "Hello, Python 2!"

So, it’s important to keep this fact in mind to enhance your understanding. Now, let’s transition to the practical applications of the print() function:

Practical Usage of print() Function

Certainly! Here are some practical ways you can use the print() function in your programming journey:

I. Debugging and Testing

When working on your code, you can strategically place print() statements to display variable values, function outputs, or execution progress. This helps you track the flow of your program and identify any issues.

II. User Interaction

You can use Python print() to communicate with users by displaying prompts, messages, and information. It’s an essential tool for creating interactive programs that engage users.

III. Data Visualization

Printing data in a structured format can aid in visualizing information. Whether it’s tabular data, graphs, or summaries, print() helps you present data clearly and comprehensively.

IV. Logging and Diagnostics

Print statements can serve as a simple form of logging. You can use them to track program execution, record events, and troubleshoot problems in real-time.

Congratulations on diving into the world of Python print() function! You’ve just unlocked an amazing tool that will accompany you on your coding journey. Think of it as your communication bridge, allowing you to send messages, values, and insights from your code to the user's screen.

With this incredible guide, you’ve gained a deep understanding of the extensive features and potential of the Python print() function. You’ve delved into its flexibility and convenience across various scenarios – from using it with different data types like strings, integers, and floats, to exploring its applications with user input, lists, dictionaries, and even in conjunction with loops and if statements. You’ve witnessed its convenience in adjusting separators and endings, and you’ve also become adept at managing errors that might arise.

Remember, Python print() is your ally, your storyteller, and your presenter. It turns your code into a narrative that’s easy to follow and understand. So, as you continue your coding journey, use the print() function – it’s your voice in the programming world, helping you communicate and shine. Happy coding!

 
Scroll to Top