Home » Data Science

Category Archives: Data Science

Newly Updated Posts

User Defined Exception in Python

In Python, By defining a new class that inherits from the built-in Exception class or one of its subclasses, you can define your own unique exceptions in Python. An illustration of how to define a user-defined exception in Python is as follows:

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

In the example above, we define a custom exception called CustomException that inherits from the base Exception class. We also override the __init__ method to allow for passing a custom error message when creating an instance of the exception.

Here’s how you can use the custom exception in your code:

def divide_numbers(a, b):
    if b == 0:
        raise CustomException("Division by zero is not allowed.")
    return a / b

try:
    result = divide_numbers(10, 0)
    print("Result:", result)
except CustomException as e:
    print("An error occurred:", e.message)

In the above code, the divide_numbers function checks if the divisor b is zero. If it is, it raises a CustomException with a custom error message. In the try-except block, we catch the CustomException and print the error message.

Output:

An error occurred: Division by zero is not allowed.

By defining and using custom exceptions, you can create more specific and meaningful error handling in your Python programs.

Error and Exception in Python

Python uses errors and exceptions to deal with extraordinary circumstances that could arise while a programme is being executed. The usual flow of the programme is interrupted when an error or exception occurs, and Python raises an error or exception object to specify the error’s kind and specifics. Try-except blocks can be used to handle these mistakes and exceptions. Here is an illustration of how Python handles errors and exceptions:

# Example 1: Handling a specific exception

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 2: Handling multiple exceptions

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 3: Handling any exception (generic exception)

try:
    file = open("nonexistent_file.txt", "r")
    content = file.read()
    file.close()
    print("Content:", content)
except Exception as e:
    print("Error:", str(e))

In the first example, a ,ZeroDivisionError, exception is handled if the user enters zero as the second number for division. In the second example, both 'ValueError and ZeroDivisionError' exceptions are handled, depending on the user’s input. In the third example, a generic Exception is caught, which can handle any type of exception. The 'as' keyword allows you to access the exception object, which can be useful for printing error messages or retrieving specific information about the error.

Nzec exception in python

NZEC stands for “Non-Zero Exit Code” exception in Python. When a programme ends with a non-zero status code, which denotes that an error or exception occurred during execution, it often happens. This exception is frequently seen in coding competitions or on websites like CodeChef or HackerRank.

Here’s an example that can trigger the NZEC exception:

# Example 1: Division by zero

try:
    a = 10
    b = 0
    result = a / b
    print(result)
except ZeroDivisionError:
    print("Error: Division by zero")

In the above example, the program tries to divide the variable ‘a’ by zero, which raises a ‘ZeroDivisionError’ exception. Since this exception is not handled properly, the program will exit with a non-zero status code, resulting in an NZEC exception.

To avoid the NZEC exception, you can handle the exception appropriately, like this

# Example 2: Handling the exception

try:
    a = 10
    b = 0
    result = a / b
    print(result)
except ZeroDivisionError:
    print("Error: Division by zero")
except Exception as e:
    print("Error:", e)

In the modified example, we catch the ZeroDivisionError and print a custom error message. Additionally, we have a generic Exception block that can catch other exceptions and display a generic error message. Handling the exception prevents the program from exiting with a non-zero status code, avoiding the NZEC exception.

It’s important to note that the specific cause of an NZEC exception may vary depending on the context and platform where the code is executed. Therefore, it’s recommended to carefully analyze the error message and the code logic to identify the root cause of the exception and handle it accordingly.

Build-in exception in python

When certain faults or extraordinary circumstances arise during the execution of a programme, built-in exceptions in the Python programming language can be raised (or thrown). These exceptions, which are defined in the Python standard library, can be applied to deal with particular error kinds.

1.TypeError: Raised when an operation or function is applied to an object of inappropriate type.

# Example: TypeError
x = 10
y = '5'
z = x + y  # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'

2. ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.

# Example: ValueError
age = input("Enter your age: ")
age = int(age)  # Raises ValueError if the input cannot be converted to an integer

3. IndexError: Raised when a sequence subscript is out of range.

# Example: IndexError
numbers = [1, 2, 3]
print(numbers[3])  # Raises IndexError: list index out of range

4. KeyError: Raised when a dictionary key is not found.

# Example: KeyError
person = {'name': 'John', 'age': 30}
print(person['gender'])  # Raises KeyError: 'gender'

5. FileNotFoundError: Raised when a file or directory is requested but cannot be found.

# Example: FileNotFoundError
file_path = 'path/to/nonexistent/file.txt'
with open(file_path, 'r') as file:  # Raises FileNotFoundError
    content = file.read()

6. ZeroDivisionError: Raised when division or modulo operation is performed with zero as the divisor.

# Example: ZeroDivisionError
x = 10
y = 0
result = x / y  # Raises ZeroDivisionError: division by zero

7. ZeroDivisionError: Raised when division or modulo operation is performed with zero as the divisor.

8. ImportError: Raised when an import statement fails to find and load a module.

9. AssertionError: Raised when an assert statement fails.

10. StopIteration: Raised to signal the end of an iterator.

These are just a few examples of built-in exceptions in Python. You can also create your own custom exceptions by deriving from the base Exception class or any other built-in exception class.

Python Try except

The try and except commands are used in Python to handle errors and exceptions. They let you to manage potential exceptions that may arise while your code is being executed, preventing your program from crashing.

The basic syntax for using try and except is as follows:

try:
    # code that might raise an exception
    # ...
except ExceptionType1:
    # code to handle the exception of type ExceptionType1
    # ...
except ExceptionType2:
    # code to handle the exception of type ExceptionType2
    # ...
else:
    # optional block executed if no exceptions were raised
    # ...
finally:
    # optional block of code that will be executed regardless of whether an exception occurred or not
    # ...

Here’s a breakdown of the different parts:

  • The try block contains the code that you want to execute, which might raise an exception.
  • If an exception of type ExceptionType1 occurs in the try block, the corresponding except block will be executed. You can have multiple except blocks to handle different types of exceptions.
  • The else block is optional and is executed if no exceptions were raised in the try block.
  • The finally block is also optional and is executed regardless of whether an exception occurred or not. It is typically used for cleanup tasks, such as closing files or releasing resources.

Here’s an example that demonstrates the usage of try and except:

try:
    x = int(input("Enter a number: "))
    result = 10 / x
    print("The result is:", result)
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No exceptions were raised.")
finally:
    print("This block always executes.")

In this example, if the user enters a non-numeric value, a ValueError exception will be raised, and the corresponding except block will handle it. If the user enters zero, a ZeroDivisionError exception will be raised. If the user enters a valid number, the code in the else block will be executed. Finally, the finally block will be executed regardless of the outcome.

By using try and except, you can gracefully handle exceptions and provide appropriate error messages or alternative behavior, improving the robustness of your code.

Python Exception Handling

In Python, handling exceptions is a technique for managing any faults or unusual circumstances that may arise while a programme is being executed. It enables you to gracefully handle some errors rather than having the programme end suddenly by allowing you to catch and handle them.

Python provides a built-in mechanism for exception handling using the try-except statement. The general syntax is as follows:

try:
    # Code block where an exception might occur
except ExceptionType1:
    # Code to handle the exception of type ExceptionType1
except ExceptionType2:
    # Code to handle the exception of type ExceptionType2
...
except:
    # Code to handle any other exceptions
else:
    # Code to execute if no exception occurs
finally:
    # Code that is always executed, regardless of whether an exception occurred or not

Here’s an explanation of the different parts:

  • The try block contains the code where you anticipate an exception might occur.
  • The except block is used to catch and handle specific types of exceptions. You can have multiple except blocks to handle different types of exceptions.
  • ExceptionType1, ExceptionType2, and so on, represent the specific types of exceptions you want to handle. For example, ValueError, TypeError, or IOError.
  • If an exception occurs in the try block and matches the specified exception type, the corresponding except block is executed. If no exception occurs, the except block is skipped.
  • You can have a generic except block without specifying the exception type. It will catch any exception that is not handled by the preceding except blocks. However, it is generally recommended to catch specific exceptions whenever possible.
  • The else block is optional and contains code that will be executed if no exception occurs in the try block.
  • The finally block is also optional and contains code that will always be executed, regardless of whether an exception occurred or not. It is typically used for cleanup tasks, such as closing files or releasing resources.

Here’s an example to illustrate how exception handling works:

try:
    num1 = int(input("Enter the numerator: "))
    num2 = int(input("Enter the denominator: "))
    result = num1 / num2
    print("Result:", result)
except ValueError:
    print("Invalid input. Please enter integers.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
except Exception as e:
    print("An error occurred:", str(e))
else:
    print("Division operation completed successfully.")
finally:
    print("Exiting the program.")

In this example, if the user enters invalid input (non-integer values), a ValueError is raised and caught by the first except block. If the user enters zero as the denominator, a ZeroDivisionError is raised and caught by the second except block. Any other unhandled exceptions will be caught by the generic except block. The else block is executed if no exception occurs, and the finally block is always executed at the end, regardless of exceptions.

By using exception handling, you can ensure that your program handles errors gracefully, provides meaningful error messages, and continues executing even in the presence of exceptions

Python Switch Case

Python doesn’t have a built-in switch-case statement like some other programming languages. However, you can achieve similar functionality using other constructs. Here are a few ways to implement a switch-case-like behavior in Python:

1. If-elif-else ladder:

def switch_case(value):
    if value == 'case1':
        # code for case 1
        pass
    elif value == 'case2':
        # code for case 2
        pass
    elif value == 'case3':
        # code for case 3
        pass
    else:
        # default case
        pass

2. Dictionary mapping:

def switch_case(value):
    cases = {
        'case1': lambda: code_for_case1(),
        'case2': lambda: code_for_case2(),
        'case3': lambda: code_for_case3(),
    }
    cases.get(value, lambda: default_case_code())()

In this approach, the cases are defined as keys in the dictionary, and the corresponding code is wrapped in lambda functions. The get() method is used to retrieve the appropriate lambda function based on the given value. If the value doesn’t match any case, a lambda function for the default case is called.

3. Using classes and methods:

class SwitchCase:
    def case1(self):
        # code for case 1
        pass

    def case2(self):
        # code for case 2
        pass

    def case3(self):
        # code for case 3
        pass

def switch_case(value):
    switch = SwitchCase()
    getattr(switch, value, lambda: default_case_code())()

In this approach, you define a class with methods representing each case. The getattr() function is used to retrieve the appropriate method based on the given value. If the value doesn’t match any case, a lambda function for the default case is called.

Choose the approach that best suits your needs and coding style.

Python Break Statement

In this tutorial, we are going to learn Python Break Statement

The break command in Python is used to end or escape a loop early. It is mainly utilised with loops like for and while to abruptly break the loop’s regular flow.

When the break statement is encountered within a loop, the program jumps out of the loop and continues execution with the next statement after the loop. This allows you to skip the remaining iterations of the loop and proceed with the rest of the code.

Here’s the general syntax of the break statement:

while condition:
    # Some code here
    
    if condition:
        break
    
    # More code here

OR

for item in iterable:
    # Some code here
    
    if condition:
        break
    
    # More code here

In the above examples, the break statement is used inside a loop. If the specified condition evaluates to True, the break statement is executed, and the loop is immediately terminated. The program then continues execution with the next statement after the loop.

Here’s an example to illustrate the usage of the break statement:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        break
    print(num)

print("Loop finished")

Output:
1
2
Loop finished

In the above code, the break statement is encountered when num is equal to 3. As a result, the loop is terminated, and the program moves to the next statement after the loop, which is print("Loop finished").

Note that the break statement only terminates the innermost loop in nested loops. If you have multiple nested loops, you can use additional control flags or techniques to break out of outer loops if needed.

Remember, the break statement is a useful tool for controlling the flow of your loops and providing flexibility in your program logic.

Python If else statement

In this tutorial, we will learn If else statement in Python.

The if-else statement in Python is used to run various blocks of code depending on a specific condition. The if-else statement’s general syntax is as follows:

if condition:
    # code to be executed if the condition is True
else:
    # code to be executed if the condition is False

Here is an illustration of how to use Python’s if-else statement:

x = 10

if x > 0:
    print("x is positive")
else:
    print("x is zero or negative")

In this example, if the value of x is greater than 0, the statement x is positive will be printed. Otherwise, the statement x is zero or negative will be printed.

You can also use multiple elif (short for “else if”) statements to check for additional conditions. Here’s an example:

x = 10

if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

In this case, if x is greater than 0, the statement x is positive will be printed. If x is equal to 0, the statement x is zero will be printed. Otherwise, the statement x is negative will be printed.

Remember to indent the code blocks correctly to define the scope of each condition. Python uses indentation (typically four spaces) to group statements together.

Python Loop

Explore our Python tutorials for beginners In this Tutorial , we will learn looping concepts in Python.

In Python, loops are used to repeat a specific block of code multiple times. They allow you to iterate over a sequence of elements or execute a block of code until a specific condition is met. Python provides two types of loops: the for loop and the while loop.

1. For Loop: The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It has the following syntax:

for variable in sequence:
    # code block

Here, variable is a variable that takes on the value of each element in the sequence during each iteration. The code block under the loop is executed for each element in the sequence.

Example 1: Printing each element of a list using a for loop:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Example 2: Calculating the sum of numbers in a range using a for loop:

total = 0

for num in range(1, 6):

total += num

print(total)

2. While Loop: The while loop repeatedly executes a block of code as long as a given condition is true. It has the following syntax:

while condition:
    # code block

The code block is executed as long as the condition remains true. If the condition becomes false, the loop is terminated, and the program continues with the next statement after the loop.

Example 1: Printing numbers from 1 to 5 using a while loop:

num = 1
while num <= 5:
    print(num)
    num += 1

Example 2: Finding the factorial of a number using a while loop:

num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print(factorial)

It’s important to ensure that the loop condition eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop.

Both for and while loops can be controlled using statements like break (to exit the loop) and continue (to skip the current iteration and move to the next).