IO in Python



1. Input Operations:
Input operations in Python enable interaction with users, allowing the program to receive data from external sources such as the keyboard or other input devices. Python offers several methods for taking input.

### Reading Input from the User:
```python
# Using input() function to take user input
name = input("Enter your name: ")
print("Hello,", name)
```

### Parsing Input:
```python
# Parsing integer input
num = int(input("Enter a number: "))
print("You entered:", num)
```

### Handling Input Errors:
```python
# Handling input errors
try:
    age = int(input("Enter your age: "))
    print("You are", age, "years old.")
except ValueError:
    print("Invalid input. Please enter a valid integer.")
```

2. Output Operations:
Output operations in Python involve displaying data to the user or saving it to external destinations such as files or databases.

### Printing Output:
```python
# Printing output to the console
print("Hello, World!")
```

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

### Writing to Files:
```python
# Writing to a file
with open("output.txt", "w") as file:
    file.write("This is a sample text.")
```

### Reading from Files:
```python
# Reading from a file
with open("input.txt", "r") as file:
    data = file.read()
    print(data)
```

3. Standard Input, Output, and Error Streams:
Python provides three standard streams: stdin, stdout, and stderr. These streams are predefined and automatically available for input and output operations.

### Standard Input:
```python
import sys

# Reading from standard input
input_data = sys.stdin.readline()
print("Input:", input_data)
```

### Standard Output:
```python
# Writing to standard output
sys.stdout.write("This is standard output\n")
```

### Standard Error:
```python
# Writing to standard error
sys.stderr.write("An error occurred\n")
```

 

Contact us for software training, education or development










 

Post a Comment

0 Comments

Me