You are currently viewing Simple input output operations in Python
Python | Operations

Simple input output operations in Python

1. Reading user input with input():

The input() function allows you to read user input from the console. Here’s an example:

# Ask the user for their name and age
name = input("What is your name? ")
age = input("How old are you? ")

# Print a personalized message
print("Hello, " + name + "! You are " + age + " years old.")

2. Writing output to the console with print():

The print() function allows you to write output to the console. Here’s an example:

# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Print each number on a separate line
for number in numbers:
    print(number)

3. Reading and writing to files with open():

The open() function allows you to read and write to files on your computer. Here’s an example:

# Open a file for writing
with open("output.txt", "w") as file:
    # Write some text to the file
    file.write("This is some text.")

# Open the file for reading
with open("output.txt", "r") as file:
    # Read the text from the file
    text = file.read()

# Print the text
print(text)

These examples demonstrate some of the basic input/output operations in Python. As you continue to learn Python, you’ll discover many more advanced techniques for reading and writing data, working with files, and interacting with users.

4. Formatting output with str.format():

The str.format() method allows you to format output strings with variables and other data types. Here’s an example:

# Define some variables
name = "Alice"
age = 25
city = "New York"

# Format a message with the variables
message = "My name is {}, I am {} years old, and I live in {}.".format(name, age, city)

# Print the message
print(message)

5. Reading and writing CSV files with the csv module:

The csv module allows you to read and write comma-separated value (CSV) files, which are commonly used to store tabular data. Here’s an example:

import csv

# Open a CSV file for writing
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)

    # Write some data to the file
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "New York"])
    writer.writerow(["Bob", 30, "San Francisco"])

# Open the CSV file for reading
with open("data.csv", "r", newline="") as file:
    reader = csv.reader(file)

    # Read the data from the file
    for row in reader:
        print(row)

These examples demonstrate some of the more advanced input/output operations in Python. As you continue to learn Python, you’ll discover many more techniques and libraries for working with different data formats and sources.

Leave a Reply