You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-**SyntaxError**: The error Python raises when your code does not follow its syntax rules. For example, the code `print("Hello there"` will lead to a syntax error with the message, `SyntaxError: '(' was never closed`, because the code is missing a closing parenthesis.
13
+
-**NameError**: Python raises a `NameError` when you try to access a variable or function you have not defined. For instance, if you have the line `print(username)` in your code without having a `username` variable defined first, you will get a name error with the message `NameError: name 'username' is not defined`.
14
+
-**TypeError**: This is the error Python throws when you perform an operation on two or more incompatible data types. For example, if you try to add a string to a number, you'll get the error `TypeError: can only concatenate str (not "int") to str`.
15
+
-**IndexError**: You'll get an `IndexError` if you access an index that does not exist in a list or other sequences like tuple and string. For example, in a `Hello world` string, the index of the last character is `11`. If you go ahead and access a character this way, `greet = "hello world"; print(greet[12])`, you'll get an error with the message `IndexError: string index out of range`.
16
+
-**AttributeError**: Python raises this error when you try to use a method or property that does not exist in an object of that type. For example, calling `.append()` on a string like `"hello".append("!")` will lead to an error with the message `AttributeError: 'str' object has no attribute 'append'`.
13
17
14
-
## Second topic
18
+
## Good Debugging Techniques in Python
15
19
16
-
Describe
20
+
-**Using the `print` function**: Inserting `print()` statements around various points in your code while debugging helps you see the values of variables and how your code flows.
21
+
-**Using Python's Built-in Debugger (`pdb`)**: Python provides a `pdb` module for debugging. It's a part of the Python's standard library, so it's always available to use. With `pdb`, you can set a trace with the `set_trace()` method so you can start stepping through the code and inspect variables in an interactive way.
22
+
-**Leveraging IDE Debugging Tools**: Many integrated development environments (IDEs) and code editors like Pycharm and VS Code offer debugging tools with breakpoints, step execution, variable inspection, and other debugging features.
23
+
24
+
## Exception Handling
25
+
26
+
-**`try...except`**: This is used to execute a block of code that might raise an exception. The `try` block is where you anticipate an error might occur, while the `except` block takes a specified exception and runs if that specified error is raised. Here's an example:
27
+
28
+
```py
29
+
try:
30
+
print(22/0)
31
+
exceptZeroDivisionError:
32
+
print('You can\'t divide by zero!')
33
+
# You can't divide by zero!
34
+
```
35
+
36
+
You can also chain multiple `except` blocks so you can handle more types of exceptions:
37
+
38
+
```py
39
+
try:
40
+
number =int(input('Enter a number: '))
41
+
print(22/ number)
42
+
exceptZeroDivisionError:
43
+
print('You cannot divide by zero!')
44
+
# You cannot divide by zero! prints when you enter 0
45
+
exceptValueError:
46
+
print('Please enter a valid number!')
47
+
# Please enter a valid number! prints when you enter a string
48
+
```
49
+
50
+
-**`else` and `finally`**: These blocks extend `try...except`. If no exception occurs, the `else` block runs. The `finally` block always runs regardless of errors.
51
+
52
+
```py
53
+
try:
54
+
result =100/4
55
+
exceptZeroDivisionError:
56
+
print('You cannot divide by zero!') # This will not run
-**Exception Object**: This lets you access the exception itself for better debugging and printing the direct error message. To access the exception object, you need to use the `as` keyword. Here's an example:
64
+
65
+
```py
66
+
try:
67
+
value =int('This will raise an error')
68
+
exceptValueErroras e:
69
+
print(f'Caught an error: {e}')
70
+
# Caught an error: invalid literal for int() with base 10: 'This will raise an error'
71
+
```
72
+
73
+
-**The `raise` Statement**: This allows you to manually raise an exception. You can use it to throw an exception when a certain condition is met. Here's an example:
74
+
75
+
```py
76
+
defdivide(a, b):
77
+
if b ==0:
78
+
raiseZeroDivisionError('You cannot divide by zero')
79
+
return a / b
80
+
```
81
+
82
+
## Exception Signaling
83
+
84
+
The `raise` statement is also useful when you create your own custom exceptions, as you can use it to throw an exception with a custom message. Here's an example of that:
85
+
86
+
```py
87
+
classInvalidCredentialsError(Exception):
88
+
def__init__(self, message="Invalid username or password"):
89
+
self.message = message
90
+
super().__init__(self.message)
91
+
92
+
deflogin(username, password):
93
+
stored_username ="admin"
94
+
stored_password ="password123"
95
+
96
+
if username != stored_username or password != stored_password:
97
+
raise InvalidCredentialsError()
98
+
99
+
returnf"Welcome, {username}!"
100
+
```
101
+
102
+
Here's a how you can use the `login` function from the `InvalidCredentialsError` exception:
103
+
104
+
```py
105
+
# failed login attempt
106
+
try:
107
+
message = login("user", "wrongpassword")
108
+
print(message)
109
+
except InvalidCredentialsError as e:
110
+
print(f"Login failed: {e}")
111
+
112
+
# successful login attempt
113
+
try:
114
+
message = login("admin", "password123")
115
+
print(message)
116
+
except InvalidCredentialsError as e:
117
+
# This block is not executed because the login was successful
118
+
print(f"Login failed: {e}")
119
+
else:
120
+
# The else block runs if the 'try' block completes without an exception
121
+
print(message)
122
+
```
123
+
124
+
The `raise` statement can also be used with the `from` keyword to chain exceptions, showing the relationship between different errors:
125
+
126
+
```py
127
+
defparse_config(filename):
128
+
try:
129
+
withopen(filename, 'r') asfile:
130
+
data =file.read()
131
+
returnint(data)
132
+
exceptFileNotFoundError:
133
+
raiseValueError('Configuration file is missing') fromNone
134
+
exceptValueErroras e:
135
+
raiseValueError('Invalid configuration format') from e
0 commit comments