PYTHON EXCEPTION FILE CONTRLO FLOW
PYTHON EXCEPTION FILE CONTRLO FLOW
PYTHON EXCEPTION FILE CONTRLO FLOW
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:
print(10 / number)
except ZeroDivisionError:
except ValueError:
- `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:
except ValueError:
print("Invalid input")
finally:
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:
result = 10 / num
except ZeroDivisionError:
else:
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:
check_age(age)
except NegativeAgeError as e:
print(e)
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.
# File operations
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
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
a, b = b, a
print("a:", a) # Output: 10
print("b:", b) # Output: 5
for i in range(5):
if i == 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:
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:
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:
# Output: (Nothing will be printed because the loop was broken when i == 3)
def test_value(value):
match value:
case 1:
print("It's one")
case 2:
print("It's two")
case _:
### 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:
if user_input.lower() == 'exit':
break
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.
- **`'r'`**: Read (default mode). Opens the file for reading. The file must exist.
**Example:**
```python
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
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
- **`'b'`**: Binary mode. Used for binary files, like images or audio.
**Example:**
```python
content = file.read()
```
- **`'x'`**: Exclusive creation. Opens the file for writing, but it fails if the file
already exists.
**Example:**
```python
```
- **`'r+'`**: Read and write. Opens the file for both reading and writing. The file
must exist.
**Example:**
```python
content = file.read()
```
---
You can read a file line by line using a loop, or by using the `readlines()` method.
```python
```
```python
```
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.**
**Example:**
```python
content = file.read()
print(content)
```
In this example, the file is automatically closed after the code block is finished,
preventing potential resource leaks.
---
You can use `try-except` blocks to handle exceptions while working with files.
Common exceptions include `FileNotFoundError`, `PermissionError`, and
`IOError`.
**Example:**
```python
try:
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
except PermissionError as e:
except Exception as 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