Python is a versatile programming language known for its simplicity and ease of use. One of the fundamental aspects of programming is dealing with input and output operations. In this blog, we'll explore how to handle input and output in Python, along with examples to illustrate these concepts.
Table of Contents
- Taking User Input in Python
- Displaying Output in Python
- Formatted Output
- File Input and Output (I/O) in Python
- Error Handling and Validation
- Working with Standard Streams
- Real-World Examples
1. Taking User Input in Python
Gathering input from users or external sources is referred to as input. Python provides a built-in function called input()
that simplifies capturing user input.
Example:
# Taking user input and displaying a message
name = input("Enter your name: ")
print("Hello, " + name + "! Welcome to our blog.")
In this instance, the input()
function prompts users for their name. The entered data is stored in the variable name
, which is then utilized to create a personalized welcome message.
2. Displaying Output in Python
Output involves conveying information to users, writing data to files, or presenting data in other ways. The most common method to produce output in Python is using the print()
function.
Examples:
# Printing a message
print("Welcome to the Python Input/Output Blog!")
# Printing the value of a variable
age = 25
print("Your age is:", age)
3. Formatted Output
Formatted output allows you to present data in a structured and readable manner. Python provides the format()
method and f-strings for achieving formatted output.
Using format()
:
name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
Using f-strings (Python 3.6+):
name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}")
4. File Input and Output (I/O) in Python
Python not only interacts with users but also handles reading and writing data to files. This is invaluable for preserving information beyond a program's runtime.
1. Writing to a File:
The open()
function is used to create and write to a file:
# Writing to a file
with open("my_file.txt", "w") as file:
file.write("This is some content written to the file.")
2. Reading from a File:
To read data from a file, you can employ methods like read()
, readline()
, and readlines()
:
# Reading from a file
with open("my_file.txt", "r") as file:
content = file.read()
print(content)
5. Error Handling and Validation
Effective input handling involves error detection and validation. Python's try
and except
blocks are used to catch and handle errors gracefully.
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input. Please enter a valid number.")
6. Working with Standard Streams
Python provides three standard streams: stdin
(standard input), stdout
(standard output), and stderr
(standard error).
import sys
user_input = sys.stdin.readline()
sys.stdout.write("This is standard output.\n")
sys.stderr.write("This is an error message.\n")
7. Real-World Examples
Example 1: Creating a To-Do List
with open("todo.txt", "a") as file:
task = input("Enter a task: ")
file.write(task + "\n")
print("Task added to the to-do list.")
Example 2: Reading CSV Data
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Top comments (2)
How are you colour coding your code block? Very nice 👌🏽👌🏽
Thank you
for color coding use language names in the code block
like
"