How to perform input and output operations in Python?

In Python, input and output (I/O) operations can be performed using various functions and methods. Here are some commonly used approaches for I/O operations:

1. Standard Input and Output (Console):
- `print()`: The `print()` function is used to display output on the console. It accepts one or more arguments and displays them as text.
- `input()`: The `input()` function is used to read input from the user via the console. It displays a prompt and waits for the user to enter a value, which is then returned as a string.


  # Output using print()
  print("Hello, World!")
  # Input using input()
  name = input("Enter your name: ")
  print("Hello,", name)

2. File Input and Output:
- Opening a file: To read from or write to a file, you need to open it using the `open()` function. It returns a file object that provides methods for reading from or writing to the file.
- Reading from a file: The `read()` method of the file object is used to read the entire contents of a file, while the `readline()` method reads a single line at a time.
- Writing to a file: The `write()` method of the file object is used to write text to a file. It can be called multiple times to write multiple lines or pieces of text.
- Closing a file: After performing file operations, it's important to close the file using the `close()` method to release system resources.


  # Opening a file for writing
  file = open("output.txt", "w")
  # Writing to the file
  file.write("Hello, World!\n")
  file.write("This is a sample file.")
  # Closing the file
  # Opening the file for reading
  file = open("output.txt", "r")
  # Reading from the file
  contents =
  # Closing the file

3. Formatted Output (String Formatting):
- String formatting using `%`: You can use the `%` operator to format strings by substituting placeholders with values.
- String formatting using f-strings: Introduced in Python 3.6, f-strings (formatted string literals) provide a concise and expressive way to format strings by embedding expressions within curly braces ``.


  name = "Alice"
  age = 25
  # String formatting using %
  message = "My name is %s and I am %d years old." % (name, age)
  # String formatting using f-strings
  message = f"My name is {name} and I am {age} years old."

These are some of the commonly used methods for performing I/O operations in Python. You can choose the appropriate approach based on your specific requirements, whether it's displaying output on the console, reading user input, or performing file operations.

Related Questions You Might Be Interested