DEV Community

Akash Singh
Akash Singh

Posted on

Basic Python: 8. Python Inputs & Outputs

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:

# Taking user input and displaying a message
name = input("Enter your name: ")
print("Hello, " + name + "! Welcome to our blog.")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Using f-strings (Python 3.6+):

name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}")
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

Example 2: Reading CSV Data

import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
lisag profile image
Lisa Ghosn

How are you colour coding your code block? Very nice 👌🏽👌🏽

Collapse
 
akashsingh3031 profile image
Akash Singh • Edited

Thank you

for color coding use language names in the code block
like

"

"```

"



```python
# Taking user input and displaying a message
name = input("Enter your name: ")
print("Hello, " + name + "! Welcome to our blog.")
Enter fullscreen mode Exit fullscreen mode