Input and output in Python

Input and output are important aspects of any programming language, and Python provides several ways to handle them.

1. Output: The `print()` function is used to output data to the console.

python
# Output data to the console
print("Hello, World!")

In this example, the `print()` function is used to output the text “Hello, World!” to the console.

2. Input: The `input()` function is used to get user input from the console.

python
# Get user input from the console
name = input("What is your name? ")

# Output a personalized message
print("Hello, " + name + "!")

In this example, the `input()` function is used to get the user’s name from the console. The name is then used to output a personalized message to the console.

3. Reading and writing files: Python provides several ways to read and write files. The `open()` function is used to open a file, and the `read()` and `write()` methods are used to read and write data to the file.

python
# Open a file for writing
file = open("output.txt", "w")

# Write data to the file
file.write("Hello, World!")

# Close the file
file.close()

# Open the file for reading
file = open("output.txt", "r")

# Read data from the file and output it to the console
data = file.read()
print(data)

# Close the file
file.close()

In this example, a file called `output.txt` is opened for writing using the `open()` function. The `write()` method is then used to write the text “Hello, World!” to the file. The file is then closed.

Later, the file is opened for reading using the `open()` function with the mode `”r”`. The `read()` method is used to read the data from the file, which is then output to the console using the `print()` function. Finally, the file is closed.

These are just a few examples of how input and output can be handled in Python. There are many other functions and methods available that can be used to handle more complex input and output scenarios.