Podcast
Questions and Answers
Flashcards
Exceptions
Exceptions
Built-in signals raised when errors occur during Python program execution.
try statement
try statement
A statement block used to handle exceptions in Python.
except clause
except clause
Specifies code to be executed if an exception occurs within the try block.
raise keyword
raise keyword
Signup and view all the flashcards
else clause (with try)
else clause (with try)
Signup and view all the flashcards
finally clause
finally clause
Signup and view all the flashcards
name variable
name variable
Signup and view all the flashcards
main value
main value
Signup and view all the flashcards
global keyword
global keyword
Signup and view all the flashcards
enumerate()
enumerate()
Signup and view all the flashcards
list comprehensions
list comprehensions
Signup and view all the flashcards
Study Notes
Exception Handling in Python
- Python has built-in exceptions that are raised when something goes wrong.
- Exceptions can be handled using a
try
statement. - Code that handles the exception is written in the
except
clause. - After an exception is handled, the code flow continues without program interruption.
- Example
try-except
structure:try: # Code
except Exception as e: print(e)
where the arrow indicates code which might throw an exception, and the type of exception thrown.
- Specific exceptions can be caught:
try: # Code
except ZeroDivisionError: # Code
except TypeError: # code
except: # Code (Handles all other exceptions)
- Custom exceptions can be raised using the
raise
keyword in Python.
Try with Else Clause
- The
else
clause in atry
block runs a piece of code when thetry
block is successful. - Example structure:
try: # Some code
except: # Some Code
else: # Code (This is executed only if the try was successful)
Try with Finally
- Python offers a
finally
clause which ensures execution of a piece of code irrespective of the exception. - Example structure:
try: # Some code
except: # Some code
finally: # Some Code (executed regardless of error!)
__name__ == '__main__' in Python
__name__
evaluates to the name of the module in Python from where the program is run.- If the module is run directly from the command line,
__name__
is set to the string__main__
. - This behavior is used to check whether the module is run directly or imported to another file.
Global Keyword
- The
global
keyword is used to modify the variable outside of the current scope.
Enumerate Function in Python
- The
enumerate
function adds a counter to an iterable and returns it. - Example usage:
for i, item in list1: print(i, item)
(Prints the items of list 1 with index!)
List Comprehensions
- List comprehension is an elegant way to create lists based on existing lists.
- Example
list1 = [1, 7, 12, 11, 22]
list2 = [i for item in list1 if item > 8]
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.