Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Input and Output

In this Python Input and Output tutorial, we'll cover the basics of reading and writing data in Python. We'll focus on the following topics:

  1. Basic Output: Print
  2. Basic Input: Input
  3. File I/O: Reading and Writing Files

1. Basic Output: Print

The print() function in Python is used to output data to the console. By default, it prints the data followed by a newline character.

Syntax:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Example:

print("Hello, World!")

Output:

Hello, World!

2. Basic Input: Input

The input() function in Python is used to read a line of text from the user (input from the console). It returns the input as a string.

Syntax:

input(prompt)

Example:

name = input("What's your name? ")
print(f"Hello, {name}!")

Output:

What's your name? John
Hello, John!

3. File I/O: Reading and Writing Files

To work with files, we need to open them using the open() function, which returns a file object. The most common modes are:

  • 'r': Read (default)
  • 'w': Write (truncate the file first)
  • 'a': Append
  • 'x': Create (if the file doesn't exist)

Reading from a file

with open('file.txt', 'r') as file:
    content = file.read()
print(content)

Writing to a file

with open('file.txt', 'w') as file:
    file.write('Hello, World!')

Appending to a file

with open('file.txt', 'a') as file:
    file.write('\nThis line is appended to the file.')

Reading and writing line by line

Reading:

with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())

Writing:

lines = ['Line 1', 'Line 2', 'Line 3']

with open('file.txt', 'w') as file:
    for line in lines:
        file.write(f'{line}\n')

That's it! You now have a basic understanding of how to handle input and output operations in Python. Keep practicing and exploring more advanced features to improve your skills.

  1. How to take user input in Python:

    • Description: To take user input in Python, use the input() function. It reads a line from the user and returns it as a string.
    • Code:
      user_input = input("Enter something: ")
      print("You entered:", user_input)
      
  2. Reading and writing files in Python:

    • Description: Python provides functions for reading (open() with mode 'r') and writing (open() with mode 'w') files.
    • Code (Reading):
      with open("example.txt", "r") as file:
          content = file.read()
          print(content)
      
    • Code (Writing):
      with open("example.txt", "w") as file:
          file.write("Hello, File!")
      
  3. Formatted output in Python:

    • Description: Use formatted strings (f-strings) or the format() method for formatted output in Python.
    • Code (f-strings):
      name = "Alice"
      age = 25
      print(f"Name: {name}, Age: {age}")
      
    • Code (format() method):
      name = "Bob"
      age = 30
      print("Name: {}, Age: {}".format(name, age))
      
  4. Using input() function in Python:

    • Description: The input() function is used to get user input in Python. It returns a string, and you can convert it to the desired data type if needed.
    • Code:
      age_str = input("Enter your age: ")
      age = int(age_str)
      print(f"Your age is: {age}")
      
  5. File handling in Python for input and output:

    • Description: File handling involves operations like opening, reading, writing, and closing files using the open() function.
    • Code (Read and Write):
      with open("example.txt", "r") as file:
          content = file.read()
          print(content)
      
      with open("output.txt", "w") as file:
          file.write("Writing to a file!")
      
  6. Standard input and output in Python:

    • Description: Standard input (stdin) and output (stdout) are commonly used for reading from the keyboard and printing to the console.
    • Code:
      user_input = input("Enter something: ")
      print("You entered:", user_input)
      
  7. Reading and writing to text files in Python:

    • Description: Reading and writing to text files involves using the open() function with appropriate modes ('r' for reading, 'w' for writing).
    • Code (Read and Write):
      with open("example.txt", "r") as file:
          content = file.read()
          print(content)
      
      with open("output.txt", "w") as file:
          file.write("Writing to a text file!")
      
  8. Python input validation and error handling:

    • Description: Input validation involves checking user input for correctness. Error handling with try-except blocks helps manage unexpected situations.
    • Code (Input Validation):
      while True:
          try:
              age = int(input("Enter your age: "))
              break
          except ValueError:
              print("Invalid input. Please enter a valid number.")
      print(f"Your age is: {age}")