Python Data Structures and Exception Handling
Python Data Structures and Exception Handling
To safely execute division with exception handling in Python, you can use: `try: a = int(input("Enter numerator: ")) b = int(input("Enter denominator: ")) result = a / b print("Result:", result) except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Invalid input.")`. This program prevents crashes from invalid input types or zero division by handling exceptions explicitly .
A Python dictionary is defined as an unordered collection of data values used to store data values like a map. It consists of key-value pairs where each key is unique. A dictionary can be created using curly braces `{}` with keys and values. For example, `my_dict = { "name": "Alice", "age": 25, "city": "New York" }`. Here, "name", "age", and "city" are keys with corresponding values "Alice", 25, and "New York" .
To create a package in Python, organize files into a directory with an `__init__.py` file. For example, `my_package/` containing `__init__.py` and `module1.py` with content `def add(a, b): return a + b`. A main program (`main.py`) imports this package using `from my_package import module1` and can then utilize `module1.add(10, 5)`, resulting in `Addition: 15`. This structure allows for modular, maintainable, and reusable code .
The `os` module in Python provides various functions that allow interaction with the operating system. It is used for file handling, directory management, and process management. Functions include `os.name` to return the name of the operating system, `os.getcwd()` to get the current working directory, and `os.mkdir("new_folder")` to create a new directory. These functionalities are critical for applications needing to manage system resources and environments efficiently .
A Python program to check if a key exists in a dictionary uses the `in` operator. For example: `my_dict = { "name": "John", "age": 30, "city": "Delhi" }`. Using `key_to_check = "age"`, you can check its existence with `if key_to_check in my_dict`. If it exists, the program could output: `Key 'age' exists with value: 30` .
In Python, exceptions are events that occur during program execution that disrupt the normal flow of instructions, typically caused by logical errors. Errors, on the other hand, are serious problems that a program cannot handle such as syntax errors. Exceptions can be managed using try-except blocks which handle exceptions gracefully without crashing the program. For instance, `try: x = 5 / 0 except ZeroDivisionError: print("Cannot divide by zero.")` prevents termination upon encountering a division by zero exception .
Python sets support mathematical operations like union, intersection, difference, and symmetric difference. Union (`|`) combines elements from both sets, intersection (`&`) finds common elements, difference (`-`) identifies elements in one set but not the other, and symmetric difference (`^`) identifies elements that are in either of the sets but not in both. These operations are helpful for tasks involving group memberships or filtering data efficiently .
Tuples, lists, sets, and dictionaries in Python differ primarily in their syntax, order preservation, mutability, and whether duplicates are allowed. Tuples use `()` and are ordered and immutable, allowing duplicates. Lists use `[]`, are ordered, and mutable, also allowing duplicates. Sets use `{}` and are unordered, mutable, and do not allow duplicates. Dictionaries use `{key: value}` format, are ordered as of Python 3.7, mutable, and do not allow duplicated keys, with access based on key-value pairs .
Modules in Python enhance code reusability and maintenance by encapsulating functionalities such as functions, classes, and variables into a single file that can be imported and used in other programs. To create a module, write Python code in a file, such as `my_module.py` containing `def greet(name): return f"Hello, {name}"`. This module can be imported using `import my_module` in other scripts to call `my_module.greet("World")`, thus reusing the `greet` function efficiently .
User-defined exceptions in Python are custom exceptions created by extending the base Exception class, allowing for handling specific conditions unique to a program's logic. For example, `class AgeTooSmallError(Exception): pass` defines a new exception. A program can raise this exception with: `age = int(input("Enter your age: ")) if age < 18: raise AgeTooSmallError else: print("You are eligible to vote.") except AgeTooSmallError: print("Error: Age is too small to vote.")`, allowing controlled responses to invalid ages .