Handle Input and Output in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn the fundamental concepts of handling input and output in Python. We will explore how to display information to the console using the print() function and how to get user input from the keyboard.

Furthermore, you will gain practical experience in writing data to files and reading data back from them. These are essential skills for any Python program that needs to interact with users or work with data stored in files.

Print Strings to the Console

In Python, the primary function for displaying output to the console is print(). Its usage is straightforward. In this step, you will practice using print() to display text.

First, locate the output.py file in the file explorer on the left side of the WebIDE. Double-click it to open it in the editor.

Add the following lines of code to output.py:

print("Hello, LabEx!")
print("This is a Python course.")

Save the file (you can use the Ctrl+S shortcut). To run this script, open the terminal at the bottom of the WebIDE and execute the following command. The terminal should already be in the ~/project directory.

python ~/project/output.py

You will see the following output in the terminal:

Hello, LabEx!
This is a Python course.

The print() function can also accept multiple arguments separated by commas. By default, it prints them with a single space in between.

Modify the output.py file, replacing its content with the following line:

print("Apple", "Banana", "Orange", "Grape", "Watermelon")

Save the file and run it again from the terminal:

python ~/project/output.py

The output will be:

Apple Banana Orange Grape Watermelon

You can customize the separator by using the sep parameter. The default value for sep is a space (' '). Let's change it to a vertical bar.

Modify output.py one more time:

print("Apple", "Banana", "Orange", "Grape", "Watermelon", sep=" | ")

Save and run the script:

python ~/project/output.py

The output now uses your custom separator:

Apple | Banana | Orange | Grape | Watermelon

This demonstrates how you can control the format of your console output.

Get User Input from the Keyboard

So far, our scripts have only displayed predefined content. To make programs more interactive, we need to get input from the user. In Python, you can do this with the input() function.

Find and open the interactive.py file in the WebIDE's file explorer. Add the following code to it:

name = input("Please enter your name: ")
print("Your name is:", name)

The input() function displays a prompt to the user (the string you pass to it) and waits for them to type something and press Enter. The text entered by the user is then returned as a string, which we store in the name variable.

Save the file and run the script from the terminal:

python ~/project/interactive.py

The script will pause and display the prompt. Type a name and press Enter.

Please enter your name: Labex User
Your name is: Labex User

The script captures your input and uses it in the final print() statement. This is a fundamental technique for creating interactive command-line applications.

Write Data to a File

Reading from and writing to files are common and essential I/O operations. Python provides the built-in open() function to handle files.

The basic syntax is open(filename, mode). The mode argument specifies how the file will be used. Common modes include:

  • 'w': Write mode. Creates a new file for writing. If the file already exists, its content is erased.
  • 'r': Read mode. Opens an existing file for reading. This is the default mode.
  • 'a': Append mode. Opens a file to add content to its end. If the file doesn't exist, it is created.

The recommended way to work with files is using the with statement, which automatically closes the file for you, even if errors occur.

Let's practice by writing some text to a file. Open the file_io.py file in the WebIDE editor and add the following code:

with open("book.txt", "w") as f:
    f.write("Bed before bright moonlight,\n")
    f.write("Suspected to be frost on the ground.\n")
    f.write("Head held high, gazing at the bright moon,\n")
    f.write("Head bowed low, thinking of my homeland.")

This code opens a file named book.txt in write mode ('w'). The f.write() method writes strings to the file. The \n character represents a newline, so each write call ends on a new line.

Save the file and run the script from the terminal:

python ~/project/file_io.py

This command will not produce any console output, but it will create a new file named book.txt in your ~/project directory. You can view its content using the cat command in the terminal:

cat ~/project/book.txt

The output should be the text you wrote to the file:

Bed before bright moonlight,
Suspected to be frost on the ground.
Head held high, gazing at the bright moon,
Head bowed low, thinking of my homeland.

Using the with statement is a best practice because it ensures the file is properly closed after the block of code is executed.

Read Data from a File

Now that we have created and written to book.txt, let's learn how to read its content. Python offers several methods for reading files. We will explore the most common ones.

We will continue working with the file_io.py script. You will add code to read the file you just created.

The read() Method

The read() method reads the entire content of a file and returns it as a single string.

Append the following code to the end of your file_io.py script. This will make the script first write the file, and then read it back and print its content.

## The writing code from the previous step should be above this

print("\n--- Reading entire file with read() ---")
with open("book.txt", "r") as f:
    content = f.read()
    print(content)

Save the file and run it from the terminal:

python ~/project/file_io.py

The output will now include the content of book.txt printed to the console:

--- Reading entire file with read() ---
Bed before bright moonlight,
Suspected to be frost on the ground.
Head held high, gazing at the bright moon,
Head bowed low, thinking of my homeland.

Iterating Over Lines

A more memory-efficient way to read a file, especially a large one, is to process it line by line. You can do this by iterating directly over the file object in a for loop.

Now, append this next block of code to file_io.py:

print("\n--- Reading file line by line ---")
with open("book.txt", "r") as f:
    for line in f:
        print(line, end='')

Here, end='' in the print() function prevents it from adding an extra newline, since each line read from the file already ends with a newline character (\n).

Save and run the script again:

python ~/project/file_io.py

The output for this section will be identical to the read() method's output, but the underlying process is different, reading one line at a time.

The readlines() Method

The readlines() method reads all lines from a file and returns them as a list of strings.

Finally, append this last block of code to file_io.py:

print("\n\n--- Reading all lines with readlines() ---")
with open("book.txt", "r") as f:
    all_lines = f.readlines()
    print(all_lines)

Save and run the script one last time:

python ~/project/file_io.py

The output for this section will be a Python list, where each element is a string representing a line from the file:

--- Reading all lines with readlines() ---
['Bed before bright moonlight,\n', 'Suspected to be frost on the ground.\n', 'Head held high, gazing at the bright moon,\n', 'Head bowed low, thinking of my homeland.']

You have now practiced the fundamental methods for both writing to and reading from files in Python.

Summary

In this lab, you have learned the fundamental techniques for handling input and output in Python. You started by using the print() function to display formatted text to the console, including how to customize separators. You then moved on to making your programs interactive by capturing user input from the keyboard with the input() function.

Finally, you explored file I/O operations. You learned how to write data to a file using open() in write mode with the recommended with statement. You also practiced reading data back from a file using various methods, including read(), iterating line-by-line, and readlines(). These skills are foundational for building more complex Python applications that interact with users and data.