2.6 Input and Output (I/O)
Input and output (I/O) operations are essential for interacting with users and external sources like files. Python provides simple and flexible methods for reading input from the user and displaying output. This section will cover how to get user input using the input()
function and how to display output using the print()
function. We'll also explore formatted output and basic file handling.
2.6.1 User Input with input()
The input()
function allows you to take input from the user as a string. It pauses the program, waits for the user to enter a value, and then returns that value as a string.
2.6.1.1 Basic Input
To prompt the user for input:
name = input("Enter your name: ")
print(f"Hello, {name}!")
Example:
Enter your name: Alice
Hello, Alice!
The value returned by input()
is always a string, so if you need to work with integers or floats, you must explicitly convert the input.
2.6.1.2 Input Conversion
You can convert the user’s input to another data type, such as an integer or a float, using type conversion functions like int()
or float()
.
Example:
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
Example of converting input to a float:
price = float(input("Enter the price: "))
print(f"The price is ${price:.2f}.")
2.6.2 Output with print()
The print()
function is used to display output to the console. You can print strings, variables, and even multiple items in a single statement.
2.6.2.1 Basic Output
print("Hello, World!") # Output: Hello, World!
You can pass multiple arguments to print()
and separate them with commas. By default, Python inserts a space between the items.
Example:
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 25
2.6.2.2 Controlling the Separator
You can change the default separator between items using the sep
parameter.
Example:
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry
2.6.2.3 Controlling the End of Output
By default, print()
ends with a newline character (\n
). You can change this using the end
parameter.
Example:
print("Hello", end=" ")
print("World!")
# Output: Hello World!
2.6.3 String Formatting for Output
Python offers several ways to format strings, making it easier to insert variables and expressions into output.
2.6.3.1 Old-Style Formatting (%
Operator)
The %
operator is used to insert values into a string with placeholders (%s
, %d
, %f
, etc.).
Example:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Alice and I am 25 years old.
2.6.3.2 format()
Method
The format()
method allows you to insert values using curly braces {}
as placeholders.
Example:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.
You can also use named placeholders:
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
2.6.3.3 f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings provide a clean and efficient way to format strings. You embed expressions directly in the string, preceded by an f
:
Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
F-strings also support expressions inside the placeholders:
print(f"Next year, I will be {age + 1} years old.")
2.6.4 Reading and Writing to Files
File I/O allows you to read from and write to files. This is useful when you need to save data or read data from external sources.
2.6.4.1 Opening a File
In Python, you use the open()
function to open a file. The open()
function takes two arguments: the filename and the mode in which the file should be opened.
Common modes include:
'r'
: Read mode (default)'w'
: Write mode (overwrites the file if it exists)'a'
: Append mode (adds to the end of the file)'b'
: Binary mode (used for non-text files, like images)
Example of opening a file for reading:
file = open("example.txt", "r")
Example of opening a file for writing:
file = open("example.txt", "w")
2.6.4.2 Writing to a File
To write to a file, use the write()
method. Don't forget to close the file when you're done writing to it.
Example:
file = open("output.txt", "w")
file.write("Hello, World!")
file.close()
2.6.4.3 Reading from a File
To read from a file, use the read()
method or readline()
to read line by line.
Example of reading the entire content of a file:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Example of reading line by line:
file = open("example.txt", "r")
for line in file:
print(line.strip()) # Strip removes newline characters
file.close()
2.6.4.4 Using with
to Handle Files
It’s common to use the with
statement when working with files. This ensures the file is properly closed after the block of code is executed, even if an error occurs.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
In this case, Python automatically closes the file when the block is exited.
2.6.5 Handling Errors During I/O Operations
Sometimes, errors occur when performing I/O operations, such as trying to open a file that doesn’t exist. You can handle these situations using exception handling.
Example of handling file-related errors:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
2.6.6 Summary
input()
is used to take input from the user. The input is always returned as a string and can be converted to other data types as needed.print()
is used to display output to the console. It can print strings, variables, and multiple items, with control over separators and the end of the output.- String formatting allows you to insert variables into strings using the
%
operator,format()
method, or f-strings for more readable and concise formatting. - File I/O allows you to read from and write to files using the
open()
function. It's good practice to use thewith
statement for proper resource management. - Handling I/O errors ensures that your program can manage unexpected situations like missing files.
Understanding input and output operations is crucial for interacting with users and handling external data sources in your Python programs. These basic I/O operations are the foundation for more advanced topics like data processing and file management.