Printing in Python

Printing the Output of Python Program

When you run a Python program, the program produces the output of the program. Python has a built-in function, print() for printing the output of your program.

This print() function enables you to view the output result of the program.

On this page, you”ll learn:

  • What the print() function is
  • How the print() function is used to view the output of your programs
  • How Printing in Python is done
  • How to format the program’s output
  • An output formating method called f-string to embed expressions inside string literals
  • The concept of passing an argument
  • What embedded variables are and how they are used
  • How to use the print() function with sep and end parameters

A Brief Introduction To Python Functions

What is a Function? A function is a block of reusable code that can be used anywhere in your program just by typing the function’s name in your program. The functions make your program less lengthy and easy to read and understand.

Built-in Functions: Python has many built-in functions. One of these functions is the print()function. Printing in Python is done using the print()function

print() Function

On the Python Variables page, you learned about Python variables. With this background, we are ready to do some simple programming.  When you write a program and run it, how would view the result (output) of the program? Python provides a function, called print(). The print() function can send the output of the program to the computer screen, and the print() function can print numbers stored in variables.  It can also print text stored in string variables.

The print() function lets you see (or print) a value stored in any memory location. We have briefly used the print() function in the Python Variables page. Going back to our example of variable “My_Age”, we have already seen on the Python Variables page how the print() function is used to print contents of variable “My_Age”.

We will write a lot of programs in the following chapters. To view the results of computations done by the Python programs, we will use the print()function extensively. So, let us see how the print()function works.

print() Function Syntax

The following is the print()function syntax. To print the value of a variable, you write the following statement in your program.

>>> print(argument1, argument2,…..)

The text inside the parenthesis are called arguments. A list of comma-separated list of arguments that you want to print is passed to the print()function.

Note: we will discuss passing the parameters in detail in a later chapter.

Printing in Python – Strings

On the Python Variables chapter, we saw how Python can print numbers contained in variables. We printed the value contained in the variable ‘My_Age’ in that chapter. Now let us write some programs that will print string variables.  In this program, we will use an example string for the dinosaur’s length.  The simple program below prints a string variable.

First, we define a variable for a string Let’s call it “Rex” and assign it a string “Tyrannosaurs Rex was 40 feet long!!”.

Then, we use the print() function to print value contained in string variable labeled “Rex”.

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> Rex = "Tyrannosaurs Rex was 40 feet long!!"
>>> print(Rex)
Tyrannosaurs Rex was 40 feet long!!
>>>

In the above program, we defined a string variable (label) named “Rex” which contains a string value “Tyrannosaurus Rex was 40 feet long!!”

To check what variable “Rex” memory location contains, we use the print() function.  The text within the parenthesis is called the argument. By typing the name of the variable (in this case “Rex”) within the parenthesis, the print(Rex) statement will print the data contained in the string variable “Rex”. As mentioned earlier, “Rex” is the argument in this case and this process is called passing the argument.

Note that the string is enclosed between double quotes. You may also use single quotes. See below.

PROGRAM EXAMPLE: CONCEPT OF PASSING AN ARGUMENT
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> Rex = 'Tyrannosaurus was 40 feet long!!'
>>> print(Rex)
Tyrannosaurus was 40 feet long!!  

Printing in Python – String Literals

What is a string literal? Strings that have not been assigned to a variable are called string literals.

An example of string literal is:

“Tyrannosaurus was 40 feet long!!”

Note the above string is not assigned to any variable.

An example of string variable is:

Rex = “Tyrannosaurus was 40 feet long!!”

Here the string is assigned to variable ‘Rex’.

You can print string literals as in the below program.

PROGRAM EXAMPLE: HOW TO PRINT STRING LITERALS
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print("Tyrannosaurus Rex was 40 feet long!!")
Tyrannosaurus Rex was 40 feet long!!
>>>

Python Multi-line Strings

You may have situations where the string is very long. Suppose you have an assignment to write a paragraph about dinosaur.  You decide to do it by writing a Python program. Since it will be a long paragraph, it will go over multiple lines. You will use Python’s multi-line string feature to write your paragraph. Multi-line strings can be printed using triple quotes (”’).

PROGRAM EXAMPLE: HOW TO PRINT MULTI-LINE STRINGS
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> Rex ='''Tyrannosaurus Rex was about 40 feet long.
It weighed about 20000 pounds.
It was a two-legged dinosaur.'''
>>> print(Rex)
Tyrannosaurus Rex was about 40 feet long.
It weighed about 20000 pounds.
It was a two-legged dinosaur.
>>>

We will further discuss string variables and strings on the Data Types page.

Print Formatting in Python And Embedded Variables

In this section, we will describe a few ways to format the print() output.

Printing a string just prints the string as is.  However, most of the time, you would like to embed a variable (a number) in the string, so that if the value of the variable changes, the print() function will print the text with the new value of the variable.  These strings are called strings with embedded variables. To illustrate the print() function usage and how to output the results to the computer screen, we will use an example of Dinosaur length, weight, and height.

Printing Strings with Embedded Variables

There are instances when it is required to embed a variable value (a number) within a string before printing. In the above example, the string ‘Tyrannosaurus Rex was 40 feet long!!’) contained the number ‘40’ as part of the string. What if it is not 40 feet? Another paleontologist might find a dinosaur fossil that is 56 feet or 30 feet or a different value.  So, we should write a program so that the Tyrannosaur’s length is a variable and can be changed to any value.  This is called an embedded variable.

To achieve this, we first define a variable with the label “length”.

Then, instead of defining a variable “Rex” as

Rex = ‘Tyrannosaurs Rex was 40 feet long!’,

we define the string “Rex” as Rex = ‘Tyrannosaurs was %s feet long!’.

Here %s is a placeholder that gets replaced by the value stored in the variable “length” by the print() statement that follows. 

Note the print() statement in the below program contains %(length).  It tells Python to replace %s in the Rex string variable with the value stored in the variable “length”.

Enrichment: What do paleontologist do?

Paleontologists study the history of life on Earth based on fossils. Fossils are the remains of plants, animals, fungi, bacteria, and single-celled living things that have been replaced by rock material or impressions of organisms preserved in rock.

PROGRAM EXAMPLE: PRINTING STRINGS WITH EMBEDDED VARIABLES
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
# Example of embedded variables in strings
>>> length = 40
>>> Rex = "Tyrannosaurus Rex is %s feet long!!"
>>> print(Rex %(length))
Tyrannosaurus Rex is 40 feet long!!
>>>

Printing Strings with Two Embedded Variables

Let us embed another variable in the “Rex” string. In addition to the “length” variable, we will define a second variable called “weight”. As in the previous example, %s in the string “Rex” will be replaced by the variable “length” and the variable “weight”. 

Note that in the print() statement, the two variables (“length” and “weight”) are enclosed in parenthesis separated by comma. The parenthesis is preceded by the percent (%) symbol.

PROGRAM EXAMPLE: PRINTING STRINGS WITH TWO EMBEDDED VARIABLES
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
# Example of two embedded variables in strings
>>> length = 40
>>> weight = 20000
>>> Rex = "Tyrannosaurus Rex was %s long and weighed %s pounds"
>>> print(Rex %(length, weight))
Tyrannosaurus Rex was 40 long and weighed 20000 pounds
>>>

Note: The next few sections of this page should be read after reviewing Python Data Types page

f-strings Formatting

Python supports multiple ways to format text strings. We introduced the %-formatting in the previous section for strings with embedded variables.  Python provides a new string formatting mechanism, referred to as “f-strings”. F-strings stands for “formatted strings”.

F-strings provide a simple way to embed expressions inside string literals for formatting. The f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces { }. The expressions are replaced with their values. These values are defined as variables ahead of the f-string statement. To create an f-string, you need to prefix the string with the letter “f”.  Below is an example of formatting strings with embedded variables using f-strings.

PROGRAM EXAMPLE: f-STRING FORMATTING
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
>>> name = "Mike"
>>> age = 8
>>> print(f'My name is {name}, my age is {age}.')
My name is Mike, my age is 8.
>>>

The f-string formatting works as follows:

1. In the print statement, the string literal starts with the letter f followed by the opening quotation mark.

 2. Variable names are enclosed by curly braces {}. These variable names are replaced by their corresponding values.

The “sep” Parameter

The default separator between the arguments in the print() function is a space.  What if you would like to have a character other than a space between values? The “sep” parameter can achieve this for you. You can modify this default separator (white space) to any other character by using the “sep” parameter.  It is also used for formatting the output strings. The “sep” parameter passes an argument to the program.  This argument is the character you want to use as a separator.

If you want to separate the strings by a character (-), you would pass the argument sep = \-

If you want the separator between strings to be the character ($), you would end the print statement with sep = \$

The following program example explains the use of the “sep” parameter.

sep” and “end” parameters (see below) let you change how the strings in the print() function are printed on the screen.

The “end” Parameter

The default character in the print() function is the newline. That is, a new line is inserted by default at the end of the string.  The print() function has a parameter called “end”, which by default is ‘\n’ (the newline character).

Python gives the programmer the option to change this default to any character of your choosing so that you can end the string with any character instead of the new line.  The end parameter can be used to append any string at the end of the output of the print() statement in python.  The “end” parameter passes an argument to the program.  This argument is the character you want to use at the end of the line.  Let us see how we can use the “end” parameter in the program examples below.

Printing a List Using print(*list)

A list is a collection of items separated by commas with the whole list enclosed in square brackets.  You can use the print() function to print the list. The items in the list will be printed separated by commas. In this section, we show how to print a list data type and formatting it in different formats.  If you want the items to be printed without the square brackets, you can use the print(*list) statement.  The programs below explain how to print lists in different formats.

PROGRAM EXAMPLE: PRINTING USING print(*list), “sep”, AND “end” OPERATORS
>>> planet_list = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
>>> print(planet_list)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
>>> # Now print planet_list using *list
>>> print(*planet_list)
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
>>> # Now print planet list using * operator, separated by commas
>>> print(*planet_list, sep = ", ")
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
>>> # Now print planet list using * operator in new lines
>>> print(*planet_list, sep = "\n")
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
>>> # Now print planet list using * operator and using “end” parameter
>>> print(*planet_list, sep = ", ", end = "!")
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune!
>>>
>>> # Example for formatting email address
>>> print("MyName", "xyz.com", sep = "@")
MyName@xyz.com
>>>

Enrichment – Social Studies Connection

Before any people were on earth, there were reptiles, now known as dinosaurs that roamed the earth.  This was during the prehistoric times about 200 million ago, known as Mesozoic Era.

There were hundreds of different types of dinosaurs. Some dinosaurs were as large as 100 feet long and 50 feet high (like Brachiosaurus).  Others were as small as a chicken.  Some w ere quadrupedal (walked on four legs); some were bipedal (walked on two hind legs).  Some others had feathers and could fly.  Dinosaurs can therefore be divided into avian dinosaurs, or birds; and non-avian dinosaurs, which are all dinosaurs other than birds.

Dinosaurs lived on earth from 165 million till 66 million year ago, when they went extinct for some unexplained reason.  Their fossils are found in most of the world, which has helped scientists to learn about these reptiles. The fossil remains show that the current birds evolved from the feathered dinosaurs. Thus, bird dinosaur was the only dinosaur lineage to survive the extinction event that happened about 66 million years ago. Below table shows the size of three popular dinosaurs.

Tyrannosaurus Rex string used for Printing. Social Studies Connection
Tyrannosaurus Rex

Tyrannosaurus Rex

Tyrannosaurus rex was up to 40 feet (12.4 m) long, and about 15 to 20 feet (4.6 to 6 m) tall. The arms were only about 3 feet (1 m) long. Tyrannosaurus rex was about 5 to 7 tons in weight. The enormous skull was about 5 feet (1.5 m) long.

Brontosaurus

Brontosaurus meaning “thunder lizard” was a gigantic quadruped dinosaur.  They had very long thin necks, long whip-like tails, small heads, and four thick, pillar-like legs. They had enormous sizes and were the largest animals to have ever lived on land. They lived in North America about 150 million years ago and were herbivorous. Brontosaurus are estimated to have weighed up to 15 metric tons and measured up to 22 meters (72 ft.) long.  Brontosaurus is one of the best-known dinosaurs that has been featured in films and even on postage stamps.

Stegosaurus

Stegosaurus was a large, plant-eating dinosaur that lived about 155 million years ago in what is now western North America. Stegosaurus was about the size of a bus; was up to 25-30 feet long (8-9 m) and about 9 feet tall (2.75 m). It weighed about 6,800 pounds (3100 kg). For its big size, Stegosaurus had a small brain about the size of a walnut (weighing about 2.5 ounces (80 grams).  It had two rows of 17 bony plates along its back. It had a heavy, spiked tail. It walked on four legs; the hind legs were twice as long as its front legs.

DINOSAURLENGTHWEIGHTLIVED
Tyrannosaurus40 feet20,000 pounds (7.5 Tons)80 million years ago
Brontosaurus59 feet50,000 pounds150 million years ago
Stegosaurus25 – 30 feet6,800 pounds150 million years ago 
DINOSAUR’S DIMENSIONS

Copyright © 2019 – 2024 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights