Table of Contents » Chapter 1 : Preliminaries : Printing
Printing
Contents
Overview
We will begin our hands-on programming in Python by learning how to display text, numbers, and symbols on the computer screen. In Python programming, we call this printing and use a function called print() to print textual content on the screen. On this page, we will explore the print() function in detail, and, as you will see, we'll use this function extensively throughout this book.
In Python, we use the print() function and printing to the screen for many different reasons:
- Educational Purposes: For beginners learning Python, print() is a fundamental tool to understand how code behaves by showing the output of different operations and constructs.
- Displaying Results: We often use print() to display final results or intermediate steps for programs that perform calculations or data processing.
- Creating Simple User Interfaces: In simple command-line interfaces, print() displays information to the user, creating a basic interactive environment.
- Interactive Feedback: In programs that we write to interact with a user, print() is used to provide prompts and feedback to the user, such as instructions, errors, or status updates.
- Formatting Output: Python's print() function can be used with string (text) formatting methods to display data in a readable and formatted way.
- Debugging: One of the print() function's most common uses is to output variable values or the execution flow of a program to help debug code.
- Logging Information: Logging in programming is a common way in which we record events, such as errors, during the execution of a program. While not a replacement for a full logging system, print() can be used to log information for a simple script or during the early stages of development.
- Testing: When testing programs, print() can be used to show test results or values during the development of test cases.
- Data Exploration: In data analysis and exploration, print() is often used to quickly display the contents of a data structure like a list, dictionary, or data frames.
- File Output: While there are more efficient ways to write to files, print() can be used with the file argument to write content to a file.
Before we get started coding, it's important to be aware that Python is a case-sensitive programming language, as described here:
Recognized by its name followed by parentheses, the print() function is built into Python, meaning you can use it without any preparations or installations. Inside the parentheses, you place alphanumeric characters (the alphabet, numeric digits, and other symbols) you wish to display (print), known as arguments, enclosed in quotes if the argument is text (e.g., print("Hello, World!")). The print() function is not limited to just printing text data—it is versatile, allowing numbers, variables, and complex expressions as arguments. As you progress, you will find that the print() function is an invaluable tool in Python.
Printing Text (Strings)
Try the following examples of printing strings in your editor:Python Code:
print("Hello, World!")
print("Hello,", "World!")
print("Hello" + "," + " " + "World" + "!")
print("Hello", "World", sep=", ", end="!")
If you wrote these examples the same in your environment and ran them, the output should look like this:
Output:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
- First, note that all four variations of the print() statement in this example print the same output.
- Code Lines 1 thru 4: Study the difference in syntax between these four lines.
- Code Line 1: This is a single string Hello, World! inside the quotes (" ") so the print() function prints the contents of the quotes directly.
- Code Line 2: This line demonstrates two separate strings, Hello, and World! each inside their own set of quotes (" "). The print() function concatenates the two strings together to print them as one line of output. Pay close attention to the fact that there is no space after the comma in the first string and no space preceding the W in the second string. How does the space get in the output, then? By default, in Python, if you place separate strings in a print() function and separate them with a comma, the print() function will add one blank space between those two strings. Sometimes, this is exactly what you need (like in this example), but sometimes, you need more control over the precise output. In those cases, you might use the techniques shown in Code Lines 3 or 4.
- Code Line 3: This line demonstrates another, more precise approach to concatenation. In this case, rather than rely on the print() function to place an automatic blank space between individual strings (each enclosed in quoted (" ")), we can use the plus (+) operator to indicate how we want the strings concatenated. In this example, each piece of our overall string is separated into parts and concatenated using the plus operator.
- Code Line 4: This line demonstrates yet another approach using the print() function's sep and end arguments (see the General Form section below) to specify how to separate the two strings in the concatenated, and what symbol we want at the end of the connected output.
String concatenation is a valuable technique that combines or joins multiple strings. This operation is beneficial when creating longer or more complex strings. Python offers different ways to perform string concatenation. One of the simplest methods is using a comma (,) between strings. For example, if you have two strings, "Hello" and "world", you can concatenate them in a print statement like this:
Python Code:
print("Hello", "world")
Output
Hello world
Another method of concatenation is using the plus (+) operator. For example, if you have those same two strings, "Hello" and "world", you can concatenate them using the expression "Hello" + "world", like this:
Python Code:
print("Hello" + "world")
Output
Helloworld
Notice the problem we have, though; using the + operator our two strings have no space between them, because the + operator does exactly what we tell it to do. In this case, we said put these two strings (words) together. Without any other instructions, we get exactly what we asked for.
What if what we wanted was this:
Python Code:
Hello, world!
A comma and a space follow the word world followed by an exclamantion point? We have several options to do this. Here is the code for several approaches and then an explanation of each:
print("Hello" + ", world!")
print("Hello" + ", " + "world" + "!")
print("Hello", end=", ")
print("world!")
print("Hello", end=", ")
print("world", end="!")
print("Hello", "world", sep=", ", end="!")
Output
Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!
Code & Output Details
- Code Line 1: This line includes the comma, space, and exclamation point inside the quotes of the second string, which works and gives us the output we want (Output Line 1), but we'll see later (when we talk about variables) that including punctuation inside of a string might not be possible.
- Code Line 2: This line uses separate string objects for the ", " and the "!", which is a better approach than Line 1 because it keeps the strings separate, and we could use other strings in place of Hello and world, which would work well.
- Code Lines 3 & 4: These lines create the correct output. This approach uses the end argument of the print() function (see the table above) to have the function add ", " to the end of the string "Hello" and then the ! is included in the string "world!". This is a good use of the end argument. However, we'll see a little later (when we talk about variables) that including punctuation inside of a string might not be possible.
- Code Lines 5 & 6: These lines work together to create the correct output. This approach uses the end argument of the print() function (see the table above) to have the function add ", " to the end of the string "Hello" and the end argument to add the ! to the world string, which is a better approach as it keeps the original strings and the punctuation separate.
- Code Line 7: This line combines the use of the sep and end arguments of the print function to create our desired output all in one line, which is the best approach.
Next, try the following examples of printing numbers in your editor:
Python Code:
print(10)
print(10, 20, 30)
print(10 + 20 + 30)
If you wrote these examples the same in your environment and ran them, the output should look like this:
Output:
10
10, 20, 30
60
Code & Output Details:
- Code Line 1: We do not use quotes when printing a literal numeric value. If you enclose a number in quotes, Python will interpret it as a string (text).
- Code Line 2: We can also print more than one number in one print() function statement by separating them by commas.
- Code Line 3: This line demonstrates that we can also perform calculations inside of the print() function. The result of the calculation is the output printed on the screen.
We can also combine printing strings and numbers in a single print() function statement. The following examples demonstrate how we might combine strings and numbers in print() function statements.
Python Code:
print("Age:", 21)
print("Age: " + str(21))
print("Sum: " + str(10 + 20 + 30))
If you wrote these examples the same in your environment and ran them, the output should look like this:
Output:
Age: 21
Age: 21
Sum: 60
Code & Output Details:
- Code Line 1: This line demonstrates using the print() function to print a string and a number. In this case, the two values are separated by a comma, which, as we saw previously, automatically adds a space between the two objects. In addition, the comma in this case also separates the fact that the two objects of different types of data (a string and an integer). The print() function can print them in this form to look like they are together even though they are separate in the code.
- Code Line 2: On this line, we want to concatenate the label Age with the integer value to make one single string. In this case, we must use the casting function str() to convert the number value to a string to concatenate it with the label Age.
- Code Line 3: As we saw previously, we can perform calculations in print() function statements. In this case, because we are also string to concatenate the resulting numeric calculated value with the label Sum, we need to use casting here as well.
Every function has a general form. It is important to learn how to interpret general forms. The general form shows all of the options available for any given unit of syntax in a programming language. For example, here is the general form of the print() function:
print(object(s), sep=separator, end=end, file=file, flush=flush)
print() is the function name, and everything inside the parenthesis ( ) is the function's arguments. The following table describes each argument in the general form of the print() function:
| Argument | Description |
|---|---|
| object(s) |
Any objects in Python and any number of objects. Objects that are not a string of alphanumeric characters are converted to alphanumeric equivalents for printing. Here is an example of a print function call with two objects as arguments. For example:
The output of this print function call would be Hi Bob. Notice the space between "Hi" and "Bob". The reason for this is explained in the sep=separator argument described below.
|
| sep=separator |
Optional argument. When you specify more than one object to print in one argument list, you can also specify how those objects are separated when printed. The default is a blank space " ". You could change this to any other one or more characters by indicating it here in the second argument of the function call. For example:
This print function statement has two object arguments: "Hey" and "What's Up?", and the sep=", " indicates that when this statement runs, it should print Hey, What's up? Notice that the sep=", " includes a comma and a space after it so that when the two objects print, they will be formatted properly with a space between the comma and the next word.
|
| end=end |
Optional argument. You can use this argument to append (add) one or more characters to the end of the output. For example:
This print function statement has two object arguments, "Hi" and "Bob", and it includes end="!" which results in the output: Hi Bob!. This time, we did not have the sep argument, so we got the single default space " " as the separator between the two objects.
|
| file=file | Optional argument. This argument is used with objects that are a bit more complex than simple alphanumeric strings of characters. We will revisit this argument later in the book. |
| flush=flush | Optional argument. This argument is used to manipulate how data is handled internally, which is a bit more complex of a concept for now. We will revisit this argument later in the book. |
In Python programming, escape sequences are used within strings to represent characters that are not easily typed directly into the code. They are particularly useful in the print() function for formatting the output. An escape sequence starts with a backslash (\) followed by the character that specifies the action to be taken. Common escape sequences include \n for a new line (Enter key), \t for a tab (Tab key), \\ for a literal backslash, and \" or \' for including a literal double or single quote in a string, respectively.
Example:
print("Hello\nWorld")
Output:
Hello
World
Code Details:
- Code Line 1: This print statement includes the \n escape sequence between the words Hello and World, which causes the output to be split over two lines.
Using escape sequences allows for greater control and flexibility in how text is displayed in the output, making it easier to format complex strings. Escape sequences are a fundamental aspect of string manipulation in Python, helping to handle special characters and format text efficiently.
See the Reference Materials: Escape Sequences ↗ page for a full list of the sequences available in Python.
Read the following programming prompts and write a program that solves the problem in your programming environment. Do not read the Solution until you try to solve it yourself first. Once you have completed writing your code, run your program, click the Solution button and compare your work.
Note: There is often more than one way to write solutions in programming. Your solution may not match the solution provided below exactly, which is generally fine if you're getting the required results. Use the provided solution as an example of an approach to learn from while not interpreting it as the only "right" solution.
Problem 1
Write a Python program using the print() function to output the following contact information. Your output should match the format and lines shown here:
1234 Nowhere Street
Someplace, UT 84999
(801)555-8888
bob@smithco.com
Problem 2
Write a Python program using the print() function with two object arguments and also use the sep and end arguments to print the following output:
Wow, that's great news!
Problem 3
Write a Python program using the print() function with three object arguments to construct a (fictitious) social security number. The three object arguments should be the three sets of numbers that make up an SSN, like 123-45-6789. Also, use the sep argument to separate the three sets of numbers with a dash symbol. Here is an example of the output:
111-22-3333