PYTHON EXCEPTION FILE CONTRLO FLOW

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

PYTHON EXCEPTION ,FILE ,CONTROL FLOW

### 1. How do you handle exceptions in Python? Provide an example.

In Python, exceptions are handled using the `try` and `except` blocks. When an
error occurs in the `try` block, Python stops executing the code in that block and
jumps to the `except` block to handle the error.

try:

number = int(input("Enter a number: "))

print(10 / number)

except ZeroDivisionError:

print("Cannot divide by zero!")

except ValueError:

print("Invalid input! Please enter a number.")

### 2. What is the difference between `try-except`, `try-finally`, and `try-except-


else` blocks?

- `try-except`: Used to catch exceptions that occur in the `try` block. The code in
`except` runs if an exception is raised in the `try` block.

try:

num = int(input("Enter a number: "))

except ValueError:

print("Invalid input")

try-finally: The `finally` block is always executed, no matter whether an


exception was raised or not. It's typically used for cleanup actions like closing
files or releasing resources.
try:

file = open("test.txt", "r")

# Some file reading operations

finally:

file.close() # Ensures file is always closed

try-except-else: The `else` block runs if no exception is raised in the `try` block. If
an exception occurs, the `except` block will handle it, and the `else` block is
skipped.

try:

num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print("Result is:", result)

### 3. **How do you raise a custom exception in Python?

You can raise custom exceptions using the `raise` keyword. To create a custom
exception, you define a new class that inherits from the built-in `Exception`
class.

class NegativeAgeError(Exception)

pass

def check_age(age):

if age < 0:
raise NegativeAgeError("Age cannot be negative")

return age

try:

age = int(input("Enter your age: "))

check_age(age)

except NegativeAgeError as e:

print(e)

### 4. What is the purpose of the `assert` statement?

The `assert` statement is used for debugging purposes. It tests whether a


condition is true and if it is false, raises an `AssertionError`. You can also provide
an optional message to the error.

x=5

assert x > 0, "x should be greater than 0" # This will pass

assert x < 0, "x should be less than 0" # This will raise an AssertionError

### 5. How do you ensure resource cleanup (e.g., closing files) using exception
handling?

You can ensure resource cleanup using the `try-finally` block or with the `with`
statement. The `with` statement automatically handles the closing of resources,
like files, even if an exception is raised.

with open("test.txt", "r") as file:

# File operations

# No need to explicitly close the file; it's done automatically

In this example, the `with` statement ensures the file is closed when the block is
exited, even if an exception occurs within the block.
CONTROL FLOW

### 1. What is the significance of indentation in Python?

Indentation is crucial in Python because it is used to define the structure and


flow of the program. Unlike other programming languages that use curly braces
`{}` to define blocks of code, Python relies on indentation to indicate code blocks
such as loops, conditionals, and function definitions.

### 2. **How do you implement conditionals (`if`, `elif`, `else`) in Python?**

Conditionals allow you to execute different blocks of code based on certain


conditions.

x = 10

if x > 0:

print("x is positive")

elif x == 0:

print("x is zero")

else:

print("x is negative")

### 3. **How do you swap two variables in Python without using a temporary
variable?**

a=5

b = 10

# Swap without temporary variable

a, b = b, a
print("a:", a) # Output: 10

print("b:", b) # Output: 5

### 4. **Explain the purpose of `break`, `continue`, and `pass` statements in


Python.**

- **`break`**: It terminates the loop and exits immediately, regardless of


whether the loop's condition is still true.

for i in range(5):

if i == 3:

break # Exits the loop when i is 3

print(i)

- **`continue`**: It skips the current iteration and moves to the next iteration
of the loop.

for i in range(5):

if i == 3:

continue # Skips the iteration when i is 3

print(i)

- **`pass`**: It is a placeholder that does nothing. It’s often used when you need
to have a syntactically correct block but don’t want to implement it yet.

for i in range(5):

if i == 3:

pass # Does nothing when i is 3

else:

print(i)
### 5. **What is the use of the `else` clause in loops?**

The `else` clause in loops is executed after the loop finishes its normal iteration
(not when it is terminated by a `break` statement). It is typically used to specify
code that should run when the loop completes successfully.

for i in range(5):

if i == 3:

break

else:

print("Loop finished without break")

# Output: (Nothing will be printed because the loop was broken when i == 3)

### 6. **How does the `match-case` statement (introduced in Python 3.10)


work? Provide an example.**

The `match-case` statement allows you to match a value against several


patterns, similar to switch/case statements in other languages. It is a more
powerful and flexible alternative to `if-elif-else`.

def test_value(value):

match value:

case 1:

print("It's one")

case 2:

print("It's two")

case _:

print("It's something else")


test_value(2) # Output: It's two

test_value(5) # Output: It's something else

### 7. **How do you write a loop that runs indefinitely? How do you exit it?**

To create an infinite loop, you can use a `while` loop with a condition that
always evaluates to `True`. To exit the loop, you can use the `break` statement.

while True:

user_input = input("Type 'exit' to stop: ")

if user_input.lower() == 'exit':

break

print("You typed:", user_input)

FILE HANDLING

### 1. **What are the different file modes in Python? Provide examples of their
use.**

In Python, the `open()` function is used to open files, and you can specify
different file modes depending on what operation you want to perform.

**Common file modes:**

- **`'r'`**: Read (default mode). Opens the file for reading. The file must exist.
**Example:**

```python

with open("example.txt", "r") as file:

content = file.read()

print(content)

```

- **`'w'`**: Write. Opens the file for writing. If the file exists, it will be
overwritten. If the file doesn’t exist, it will be created.

**Example:**

```python

with open("example.txt", "w") as file:

file.write("Hello, World!")

```

- **`'a'`**: Append. Opens the file for writing, but the content is added to the
end of the file. If the file doesn’t exist, it will be created.

**Example:**

```python

with open("example.txt", "a") as file:

file.write("\nAppending new text.")


```

- **`'b'`**: Binary mode. Used for binary files, like images or audio.

**Example:**

```python

with open("image.png", "rb") as file:

content = file.read()

```

- **`'x'`**: Exclusive creation. Opens the file for writing, but it fails if the file
already exists.

**Example:**

```python

with open("new_file.txt", "x") as file:

file.write("This will only work if the file doesn't exist.")

```

- **`'r+'`**: Read and write. Opens the file for both reading and writing. The file
must exist.

**Example:**
```python

with open("example.txt", "r+") as file:

content = file.read()

file.write("\nAppending more data.")

```

---

### 2. **How do you read a file line by line in Python?**

You can read a file line by line using a loop, or by using the `readlines()` method.

**Example using a loop:**

```python

with open("example.txt", "r") as file:

for line in file:

print(line.strip()) # Use strip to remove trailing newline characters

```

**Example using `readlines()`:**

```python

with open("example.txt", "r") as file:


lines = file.readlines()

for line in lines:

print(line.strip()) # Use strip to remove trailing newline characters

```

The first approach reads the file line by line in memory-efficient way, while
`readlines()` loads all lines into a list at once.

---

### 3. **Explain the use of the `with` statement for file handling.**

The `with` statement simplifies file handling by automatically taking care of


closing the file after the block of code is executed, even if an exception occurs.
This eliminates the need to manually close the file.

**Example:**

```python

with open("example.txt", "r") as file:

content = file.read()

print(content)

# No need to call file.close() explicitly, it's automatically done

```
In this example, the file is automatically closed after the code block is finished,
preventing potential resource leaks.

---

### 4. **How do you handle exceptions while working with files?**

You can use `try-except` blocks to handle exceptions while working with files.
Common exceptions include `FileNotFoundError`, `PermissionError`, and
`IOError`.

**Example:**

```python

try:

with open("non_existent_file.txt", "r") as file:

content = file.read()

except FileNotFoundError as e:

print(f"Error: {e}")

except PermissionError as e:

print(f"Permission error: {e}")

except Exception as e:

print(f"An unexpected error occurred: {e}")

```
In this example, if the file doesn't exist, a `FileNotFoundError` is raised, and the
error is caught and handled gracefully.

---

### 5. **How do you append data to an existing file without overwriting it?**

To append data to an existing file without overwriting it, you open the file in
append mode (`'a'`), which adds new content to the end of the file.

**Example:**

```python

with open("example.txt", "a") as file:

file.write("\nThis is new content added to the file.")

You might also like