Python Reference

Links : Learn     Interview Questions     IDE
            

Python Interview Questions - Page 4

< Previous Page              Next Page >
Question: How do you handle exceptions in Python?
Answer: In Python, one can handle exceptions using the try and except blocks. Code that might raise an exception is placed inside the try block, and the handling code is placed inside the except block. For example:
try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Handling code for the ZeroDivisionError
    print("Cannot divide by zero!")
Question: How do you iterate over a dictionary in Python?
Answer: You can iterate over a dictionary in Python using a for loop. By default, the loop iterates over the dictionary keys, but you can also iterate over key-value pairs using the items() method. For example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(key, value)
Question: How do you handle multiple exceptions in Python?
Answer: You can handle multiple exceptions in Python using multiple except blocks or by specifying a tuple of exception types in a single except block. For example:
try:
    # Code that might raise exceptions
    result = 10 / 0
except (ZeroDivisionError, ValueError):
    # Handling code for ZeroDivisionError and ValueError
    print("An error occurred!")
Question: How do you handle file I/O errors in Python?
Answer: You can handle file I/O errors in Python using a try block with an except block specifically targeting the IOError or OSError exception types. For example:
try:
    with open('file.txt', 'r') as f:
        contents = f.read()
except IOError:
    print('Error: Unable to read file')
Question: What is a virtual environment in Python?
Answer: A virtual environment in Python is a self-contained directory that contains a Python interpreter and a set of libraries. It allows one to install and manage dependencies for your projects without affecting system-wide packages.

< Previous Page Next Page >