What is the difference between read(), readline(), and readlines()?

In Python, read(), readline(), and readlines() are methods of a file object that allow you to read data from a file, but they work in slightly different ways:

1. read()

  • Functionality: Reads the entire content of a file as a single string.
  • Use Case: Use it when you want to read the whole file at once.
  • Example: with open('example.txt', 'r') as file: content = file.read() print(content)
  • Note: Be cautious when working with large files, as it loads the entire file into memory.

2. readline()

  • Functionality: Reads the next line from the file (up to and including the newline character).
  • Use Case: Use it when you want to read a file line by line interactively.
  • Example: with open('example.txt', 'r') as file: line = file.readline() while line: print(line, end='') # Print each line without adding extra newline line = file.readline()
  • Note: If the file ends, readline() returns an empty string ('').

3. readlines()

  • Functionality: Reads all lines from the file and returns them as a list of strings, where each string is a line.
  • Use Case: Use it when you want to process all lines of a file but as a list.
  • Example: with open('example.txt', 'r') as file: lines = file.readlines() for line in lines: print(line, end='') # Print each line without adding extra newline
  • Note: This also reads the entire file into memory, similar to read().

Summary of Differences:

MethodReadsReturnsUse Case
read()Entire fileStringWhen you need the whole file content.
readline()One line at a timeStringWhen you want to process lines interactively.
readlines()Entire fileList of stringsWhen you want all lines but as a list.

For large files, it’s better to use readline() or iterate over the file object directly (e.g., for line in file:) to avoid memory issues.

How do you raise and handle custom exceptions?

Raising and Handling Custom Exceptions in Python

Python allows you to define and use custom exceptions by subclassing the built-in Exception class. This is useful when you want to create meaningful, domain-specific error types in your program.


1. Raising a Custom Exception

To raise a custom exception:

  1. Define a new exception class by inheriting from the Exception class (or any subclass of Exception).
  2. Use the raise keyword to trigger the exception.

Example:

# Define a custom exception
class CustomError(Exception):
    pass

# Raise the custom exception
def risky_function():
    raise CustomError("This is a custom exception!")

# Call the function
try:
    risky_function()
except CustomError as e:
    print(f"Caught an error: {e}")

Output:

Caught an error: This is a custom exception!

2. Adding Additional Attributes

Custom exceptions can include attributes and methods to provide more context about the error.

Example:

class ValidationError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

try:
    raise ValidationError("Invalid input", 400)
except ValidationError as e:
    print(f"Error: {e}, Code: {e.code}")

Output:

Error: Invalid input, Code: 400

3. Handling Custom Exceptions

You handle custom exceptions just like any other exception using try-except.

Example:

class NegativeValueError(Exception):
    pass

def check_positive(value):
    if value < 0:
        raise NegativeValueError("Negative values are not allowed!")

try:
    check_positive(-5)
except NegativeValueError as e:
    print(f"Error: {e}")

Output:

Error: Negative values are not allowed!

4. Custom Hierarchies of Exceptions

You can define a hierarchy of exceptions for better organization.

Example:

class AppError(Exception):
    """Base class for all application-related errors."""
    pass

class DatabaseError(AppError):
    pass

class NetworkError(AppError):
    pass

try:
    raise DatabaseError("Database connection failed!")
except DatabaseError as e:
    print(f"Database error: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except AppError as e:
    print(f"General app error: {e}")

Output:

Database error: Database connection failed!

5. Combining Custom Exceptions with Standard Exceptions

You can handle custom and standard exceptions together.

Example:

class CustomError(Exception):
    pass

try:
    x = int("abc")  # Raises a ValueError
    raise CustomError("Custom error occurred")
except ValueError as e:
    print(f"Value error: {e}")
except CustomError as e:
    print(f"Custom error: {e}")

Output:

Value error: invalid literal for int() with base 10: 'abc'

Best Practices

  1. Use meaningful names for custom exceptions to make them self-explanatory.
  2. Add relevant attributes to pass additional error details.
  3. Group related exceptions under a common base class for better organization.
  4. Always use try-except to gracefully handle your custom exceptions in the program.

By using custom exceptions effectively, you can improve the readability, maintainability, and robustness of your code.

How to fetch REST API data in React

In this tutorial, we will learn how to fetch REST API data and use it in react components by building a book catalogue page.Setting up a React app

Execute the following commands to set up a React app: $ npx create-react-app my_cool_app $ cd my_cool_app $ npm start

Copy the following code to /src/index.js

import React from 'react'; import ReactDOM from 'react-dom/client'; function MyApp() { return <h1> Books Available </h1>; } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

Check the app at http://127.0.0.1:3000/

Building an user interface for book catalogue.

Modify the MyApp function to show some demo books:

function MyApp() { const demo_books = [ { "id": -1, "name": "Book-Name", "author": "Author-Name" }]; const books = demo_books; // TODO: add useState() here. const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); }

Make the books variable the component’s state.

Replace the books variable initialization line with the following useState code.

// Need: import { useState } from 'react'; const [books, setBooks] = useState(demo_books)

Creating a REST API URL

Create a file book.json inside the /public directory. Add the following content to the file.


[
    {
        "id": 1,
        "name": "Code Complete",
        "author": "Steve McConnell"
    },
    {
        "id": 2,
        "name": "The Pragmatic Programmer",
        "author": "Andrew Hunt"
    },
    {
        "id": 3,
        "name": "Programming Pearls",
        "author": "Jon L. Bentley"
    }
]

You can access the books.json at http://127.0.0.1:3000/books.json

Use fetch api to retrieve REST API data.

Add the following fetch api code after the useState() code.

// Need: import { useEffect } from 'react'; useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); // empty-brackets to fetch data only once.

MyApp will get executed every time the state of the component changes. useEffect with zero-dependency will fetch the data only once. If you don’t use useEffect, the change of the books-state by fetch api will invoke the MyApp function, which contains the fetch api code. This cycle will retrieve the REST data an indefinite number of times.

If you define another state which influences the data (say total_books) , you should use the second argument to specify it so that the data will be fetched every time that state changes:  useEffect( _ , [total_books]); 

Your app will show the following output:

 

Books Available
  • Code Complete by Steve McConnell
  • The Pragmatic Programmer by Andrew Hunt
  • Programming Pearls by Jon L. Bentley

 

Here goes the complete code:

import React from 'react'; import ReactDOM from 'react-dom/client'; import { useState, useEffect } from 'react'; function MyApp() { const [books, setBooks] = useState([]) useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

 


Thanks for coming by 🙂


Python string formatting

# Welcome to TutorialShore!
# Today we will discuss Formatted String Literals
# and format method of String class in python
# Let me start writing a program to greet a student with their grade.

name = “Oyster”
grade = 8.568

message = ‘Hello ‘ + name + ‘! You scored ‘ + str(grade) + ‘.’

# ideally we want a string like
message = ‘Hello name! You scored grade.’

# To use formatted string literals (also called f-strings for short),
# begin a string with f before the opening quotation mark.
# Inside the string, you can write a Python expression or variable
# wrapped by curley brackets.

message = f’Hello {name}! You scored {grade:.2f}.’ # specify format for the field 10.2f

# You can use F instead of f and F-strings work with double and triple quotes also.

# Python String has a method called format.
# Let us explore that method
message = ‘Hello {}! You scored {:.2f}.’.format( # automatic field numbering
name, grade
)

message = ‘Hello {0}! You scored {1:.2f}. Bye {0}’.format( # manual field specification
name, grade # positional arguments
)

message = ‘Hello {name}! You scored {grade:.2f}. Bye {name} :)’.format(
name=name, grade=grade # keyword arguments
)

# The studen
student = {
“name”: “Oyster”,
“grade”: 8.456,
“subject”: “CS”
}

message = ‘Hello {name}! You scored {grade:.2f} in {subject}. Bye {name} :)’.format(
name=student[‘name’], grade=student[‘grade’], subject=student[‘subject’] # keyword arguments
)

message = ‘Hello {name}! You scored {grade:.1f} in {subject}. Bye {name} :)’.format(
**student # double asterisk operator for keyword arguments
)

print(message)