Basic Python: 8. Python Inputs & Outputs
Tags: python, beginners, programming, tutorial
Published: 2023-08-30 14:35:52

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

1. **Taking User Input in Python**
2. **Displaying Output in Python**
3. **Formatted Output**
4. **File Input and Output (I/O) in Python**
5. **Error Handling and Validation**
6. **Working with Standard Streams**
7. **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:**

```python
# 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:**

```python
# 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()`:

```python
name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
```

Using f-strings (Python 3.6+):

```python
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:

```python
# 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()`:

```python
# 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.

```python
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).

```python
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

```python
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

```python
import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
```