Python Input and Output Operations (I/O) with Examples

Input and Output Enable Us to Communicate With The Program

Input and Output operations: Input() function lets you provide data to the program. print() function outputs the result of the program with passing parameters and Output Formatting.

By the end of this Input and Output page, you will learn the following concepts:

  • How to inout data to the Python program using the input() function
  • How to view the results of your Python program using the print() function
  • How to print the different variable types such as strings, lists, integers, floating point numbers etc.
  • How to format the program output and how to specify the number of digits to be printed for floating point numbers.

This page also shows ways how to format the program’s output to make it more mwaningful to the reader.

Input and Output Operations: The input() Function

You may sometime have run into the following situation while filling out a web application. The app will ask you to enter your name, address, etc.  The app will wait until you have entered the requested data such as your name.

Once you have finished entering your name and hit the enter key, the web application program may ask you to enter your address. After you have entered the address and hit the enter key, the web app will ask you to enter some other data.

Entering the requested data is done by using the Python input() function. The input() function is a useful function for the programmer to enter the data and interact with the program via the keyboard.

Input and Output Operations: The print() Function

When a program has been run, it produces the results of the computations called the Output. Python print() function is used to view the output of the program

To show how to use the input() function and print() function, we will use the information from the Enrichment: Astronomy Related section in the Python Data Types chapter.

Let us now explore in detail how we input data into Python programs. We will also see how the Python programs output the results of the computation to the computer screen.

Input and Output – input() Function for inputting data to the Program

To input the data into the program, we use a Python function input(). We use our keyboard to input the data into the program. The input() function treats the input from the keyboard as a single line of string. Whatever you type is saved by the input() function in a variable.

The input() function reads what you type on the keyboard and stores the string in a variable named “name” as in the one-line code below.

>>> name = input()

Here is a simple example program showing the use of the input() function.

Program Example: input() Function Use Case
>>> your_name = input ("Enter your name: ")  #1)
Enter your name: John Smith                  #2)
>>> print(your_name)                         #3)
'John Smith'                                 #4)
>>>

In the program above,

Line 1) uses the input() function with the parameter “Enter your name: ” within the parenthesis.

Line 2) The input() function displays the text “Enter your name: ” on the screen. It is prompting the user to enter his or her name using the keyboard.

In this example, the user entered the text “John Smith” followed by the ENTER key. The input() function stores this text in the variable “your_name”.

Line 3) asks the program to print the contents of the variable “your_name”.

Line 4) is the output of the print statement. It shows that the variable “your_name” contains the text “John Smith”. This is the text that the user entered when prompted by the input() function. See line 2).

Input and Output – print() Function For Viewing Program Output

To display the results of program computations (the output), Python has a function called print(). We have been using the print() function in the earlier chapters. The variable that you would like the program to print is typed within the parenthesis of the print() statement.

As in the case of the input() function, the text (or the values) within the parenthesis is called the parameter.  We will provide more details of the print() function in Python Functions 1 Chapter.

Let’s use the print() function to output a string.

Printing a String Literal

To print a string, you would write the string within the parenthesis of the print() function. All text within the quotes will get printed as is on your monitor.

If the string to be printed is very long, you may want to split the output results into two or more lines. Printing the output in two or more lines is called line feed.

You can add a new line using the line feed character \n.

The program below shows how to add a line feed in the output printed by the program.

PROGRAM EXAMPLE: print() FUNCTION USE CASE FOR STRING LITERAL
>>> print('Hawaii is the 50th state of the Union')
Hawaii is the 50th state of the Union
>>> print('''California joined the Union
on September 9, 1850 as the 31st state.
September 9, 1950 is called California Admission Day.''')
California joined the Union
on September 9, 1850 as the 31st state.
September 9, 1950 is called California Admission Day.
>>> # Same as above, but use \n to go to the next line.       
>>> print('California joined the Union on September 9, 1850 \nas the 31st state of the union. \nSeptember 9, 1850 is called \nthe California Admission Day.')
California joined the Union on September 9, 1850 
as the 31st state of the union. 
September 9, 1850 is called 
the California Admission Day.
>>>

Print a String Variable

In the above section, you saw how to print a string literal. You also saw how to do line feed in the output by inserting \n line feed character in the string.

In this section, you will see how to print a string variable.

To print a variable, you first define the variable and assign it a value using the assignment operator equal (=) symbol. Then, you write the variable’s name within the parenthesis in the print() function.

If you need to print more than one variable, separate the variables list by commas. The items (text) within the parenthesis of the print() function are called arguments. Writing comma-separated variable names (arguments) inside the parenthesis of the print() statement is called passing the parameters.

In the program below, we will use the same example as in the previous program, but replace some of the names, and dates by variables as shown below.

>>> state = ‘California’

>>> date = ‘September 9’

>>> year = 1850

In the print statement, write the variables ‘state’, ‘date’, and ‘year’ separated by commas.  Python print() function will replace the variables ‘state’, ‘date’, and ‘year’ with their values ‘California’, ‘September 9’, and ‘1850’ respectively.

PROGRAM EXAMPLE: print() FUNCTION FOR STRING VARIABLE
>>> # Define a variable name state and assign it value ‘California’.
>>> state = 'California'
>>> # Define variable ‘date’ and assign a value 'September 9'.
>>> date = 'September 9'
>>> # Define a variable called 'Year' and assign a value '1850'
>>> year = 1850
>>> # Now write the print() statement using the above variables.
>>> print(state, 'joined the Union on', date , year, 'as the 31st state.')
California joined the Union on September 9 1850 as the 31st state.
>>> print(date, year, 'is called California Admission Day.')
September 9 1850 is called California Admission Day.
>>> 

Printing a List Data Type

In the above section, we saw how to print a string variable. Now let us see how we can print a list data type.

When you print a list, the print() function prints the items with quotes around the items and a square bracket around the list. The program below shows the result of printing a list.

PROGRAM EXAMPLE: PRINT a LIST
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(names)
['Sam', 'Peter', 'James', 'Julian', 'Ann']
PROGRAM EXAMPLE: PRINT a LIST WITHOUT QUOTES AND BRACKETS

If you would like to print the items in a list separated by commas; but with no quotes and no brackets, use the sep = “, “ parameter.

The following program example shows how to print a list without brackets and quotes. The star symbol (*) unpacks the list and returns every element in the list.

Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
# Now use sep = ", " to print without quotes.
print(*names, sep=", ")
Sam, Peter, James, Julian, Ann

In the above sections, we have seen how to print string and list data types variables. Now, let us see how we print numbers. Before we write programs to print numbers, let us review the two types of numbers we will come across (rational and irrational numbers) in our programs.

Rational and Irrational Numbers

You may have come across irrational numbers in your math class. The section below explains what rational and irrational numbers are.

Irrational Numbers

An irrational number is a real number that cannot be expressed as a ratio of two integers. Irrational numbers have an infinite number of digits after the decimal point. One such number is pi, which is the ratio of the circumference of a circle to its diameter. ‘pi’ (also written by the Greek letter π) is approximately 3.14159.  Since π is an irrational number, it has an infinite number of digits after the decimal point.

π = 3.1415926535 897……

Rational Numbers

A rational number, on the other hand, can be written as the ratio of two integers. Some rational numbers have a fixed number of digits after a decimal point, while others have repeating numbers after the decimal point.  This repetition goes on forever.  See the Enrichment: Number Theory section at the end of this chapter. Some examples of rational numbers are:

1/4 = 0.25 (In this case, the number of digits after the decimal point are two.)

1/2 = 0.5 (Number of digits after decimal point is one.)

There are some rational numbers whose decimal representations have one digit that keeps on repeating until infinity. One example of such numbers is 1/3 = 0.33333…..

Other rational numbers have a group of digits that repeat forever such as 1/11 = 0.09090909…… These numbers are called recurring decimal numbers

Below are a few more examples of recurring numbers.

1/3 = 0.33333333……  The repetition of ‘3’ goes on until infinity.

1/11 = 0.09090909…… The repetition of ‘09’ goes non until infinity.

Rational Numbers Program Example

The program below prints the decimal representations of several rational numbers.

Refer to the Enrichment: Number Theory section at the end of the chapter for further details about rational numbers.

PROGRAM EXAMPLE: print() FUNCTION FOR RATIONAL NUMBERS
>>> # Program examples for Rational numbers.
>>> # Rational numbers that do not have a repeating pattern
>>> # after decimal point.
>>> x = 1/3
>>> print('''Rational number that do not repeat after decimal point =''', x)
Rational number that do not repeat after decimal point = 0.3333333333333333
>>> # Rational number that repeat one digit after the decimal point until infinity.
>>> # Rational number that repeat one digit after the
>>> # the decimal point until infinity.
>>> a = 1/3
>>> 
>>> print('''1/3 decimal representation has digit '3' that repeats
until infinity =''',a)
1/3 decimal representation has digit '3' that repeats
until infinity = 0.3333333333333333
>>> b = 1/9
>>> print('''1/9 decimal representation has "1" digit that repeats
until infinity =''', b)
1/9 decimal representation has "1" digit that repeats
until infinity = 0.1111111111111111
>>> c = 1/11
>>> print('''1/11 decimal representation has digits "09" that repeats
until infinity = ''' , c)
1/11 decimal representation has digits "09" that repeats
until infinity =  0.09090909090909091
>>> d = 1/13
>>> print(d)
0.07692307692307693
>>> print('''1/13 decimal representation has six digits "076923"
that repeat until infinity =''' , d)
1/13 decimal representation has six digits "076923"
that repeat until infinity = 0.07692307692307693
>>> x = 1/7
>>> print('''1/7 decimal representation has six digits "142857"
that repeat until infinity = ''' , x)
1/7 decimal representation has six digits "142857"
that repeat until infinity =  0.14285714285714285
>>> 

Irrational Numbers Examples

As mentioned in the previous section, irrational numbers are numbers that cannot be expressed as a ratio of two integers. Irrational numbers’ decimal representation has digits that continue forever after the decimal point. Unlike rational numbers, irrational numbers have no recurring or repeating pattern of the digits after the decimal point.

Since irrational numbers cannot be expressed as a ratio of two integers and the pattern never ends, their number value is known only approximately.

A few examples of irrational numbers are the square root of 2 and the square root of 3.

Enrichment: Number Theory section at the end of this chapter has more details about irrational numbers.

Math Module Has Two Irrational Numbers PI and Euler’s Number

Python has many built-in modules that contain many useful functionalities that programmers need. One such module is the math module.  The math module has several math functions that are used in trigonometry and calculus. We will discuss the python modules in detail on the Python Modules page.

pi (π):

The math module contains a mathematical constant called pi. It is written as the Greek letter π.  ‘pi’ is an irrational number – meaning it cannot be expressed as a ratio of two integers and the number of digits after the decimal point in its decimal representation go on till infinity.

π is defined as the ratio of a circle’s circumference to its diameter. 

pi‘s value is approximately 3.14159. It can be approximated by the fraction 22/7.

The number π is discussed in more detail in Enrichment: Number Theory at the end of this chapter.

Euler’s Number (e):

Another irrational number that is found in all scientific disciplines is Euler’s Number (denoted by ‘e’). Its value is 2.718281828……..

Euler’s Number e is the base of the natural logarithm. You will come across this number in your high school math class.

Find the Value of pi Using the Math Module

In the program below, we also find out the value of ‘pi’ by using the python built-in module math.

Before you can use the modules, you need to import the module by the statement below:

>>> import module_name

In our program, we will use the following statement.

>>> import math

The program imports the math module and

  • Prints the value of pi.
  • Calculates the square root of 2 and prints its value.
  • Calculates the square root of 3 and prints its value. 

Note that the square root is calculated by raising the number to the power 0.5.

PROGRAM EXAMPLE: IRRATIONAL NUMBER PROGRAM AND USE OF MATH MODULE TO PRINT VALUE OF PI
>>> # Irrational Numbers Program Examples
>>> 
>>> x = 2**0.5
>>> print('Square root of 2 = ', x)
Square root of 2 =  1.4142135623730951
>>>
>>> # Define variable y = square root of 3 and print it
>>> y = 3**0.5
>>> print('Square root of 3 = ' ,y)
Square root of 3 =  1.7320508075688772
>>> # The following statements illustrate how to import 
>>> # math function and print value of pi.
>>> import math
>>> print(math.pi)
3.141592653589793
>>> 
Verified by MonsterInsights