Python Input / Output

Standard Input (Keyboard Input):

The input() function is used to read input from the user. It reads a line of text from the user and returns it as a string.

                                  
                                    name = input("Enter your name: ")
print("Hello, " + name + "!")
                                  
                                

Standard Output (Console Output):

The print() feature is used to show output at the console. You can print variables, strings, and combine them.

                                  
                                    age = 25
print("Your age is:", age)
                                  
                                

Formatted Output (f-strings):

Formatted strings (f-strings) make it easy to embed expressions internal string literals.

                                      
                                        name = "Alice"
age = 30
print(f"{name} is {age} years old.")
                                      
                                    

File Input/Output:

File Input/Output (I/O) in Python refers to the manner of studying from and writing to files. Python offers a easy and bendy way to engage with files the use of integrated functions and techniques.

Writing to a File:

                                      
                                        with open("example.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("This is an example.")
                                      
                                    

Reading from a File:

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

Reading and Writing Line by Line:

Reading and writing line by way of line in Python refers back to the system of reading or writing information one line at a time from or to a file. This is frequently beneficial whilst coping with big files or whilst you need to system information sequentially with out loading the complete record into reminiscence.

Python affords several approaches to achieve this, and two not unusual methods contain using the readline() method for reading and the writelines() method for writing.

Writing Lines to a File:

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

with open("example_lines.txt", "w") as file:
    for line in lines:
        file.write(line + "\n")
                                      
                                    

Reading Lines from a File:

                                      
                                        with open("example_lines.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Remove newline characters
                                      
                                    

Error Handling (try-except):

Error handling in Python is completed the usage of the attempt to except blocks. The idea is to attempt a block of code that might raise an exception, and if an exception occurs, manage it in the except block. This helps save you the program from crashing and lets in you to gracefully address mistakes.

                                      
                                        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 number.")
except Exception as e:
    print("An error occurred:", e)
                                      
                                    

Console Output Formatting (ANSI Escape Codes):

ANSI break out codes are unique sequences of characters that, while revealed to a terminal or console, can manipulate numerous formatting alternatives which include text color, background coloration, text style (ambitious, underline), and cursor positioning. These codes are usually used to feature color and formatting to console output.

Common ANSI escape codes include:

  • \033[0m: Reset all formatting (reset to default).
  • \033[1m: Bold text.
  • \033[4m: Underline text.
  • \033[91m, \033[92m, \033[93m: Set text color to red, green, or yellow, respectively.
                                      
                                        print("\033[1;31;40mHello, Python!\033[0m")
                                      
                                    

This uses ANSI escape codes to change the text color.


Reading and Writing JSON:

Reading and writing JSON (JavaScript Object Notation) in Python is a commonplace venture, as JSON is a extensively used statistics interchange layout. Python gives the json module to work with JSON statistics.

                                      
                                        import json

# Writing JSON to a file
data = {"name": "John", "age": 25, "city": "New York"}
with open("data.json", "w") as json_file:
    json.dump(data, json_file)

# Reading JSON from a file
with open("data.json", "r") as json_file:
    loaded_data = json.load(json_file)
    print("Loaded Data:", loaded_data)
                                      
                                    

These are only some examples of enter and output operations in Python. Understanding those ideas is critical for interacting with customers, coping with documents, and coping with data to your Python packages.