Session 5 - Summary 1718363016202
Session 5 - Summary 1718363016202
05 _ APSCHE
Text Files: These files contain text data and are human-readable. Examples include .txt, .csv,
and .json files. They store data in a structured format, often with lines and characters.
Binary Files: These files contain data in a format that is not human-readable and is intended
to be interpreted by programs. Examples include .bin, .jpg, .png, and .dat files. They store
data in binary form (0s and 1s).
content = file.read()
print(content)
file.close()
file.write('Hello, World!\n')
file.close()
In Python, errors and exceptions are events that disrupt the normal flow of a program's
execution. Understanding how to handle these exceptions is crucial for creating robust and
reliable programs.
Syntax Errors: These occur when the parser detects an incorrect statement. For example,
missing colons, incorrect indentation, or misspelled keywords.
Ex:
# Syntax Error Example
if True
print("This will cause a syntax error")
Exceptions: These are errors detected during execution. Common exceptions include
ZeroDivisionError, FileNotFoundError, TypeError, ValueError, etc.
Ex:
# Exception Example
result = 10 / 0 # This will raise a ZeroDivisionError
Exception Handling
Python provides a way to handle exceptions using try, except, else, and finally blocks.
try:
result = 10 / 0
except ZeroDivisionError:
try:
result = 10 / 0
except ZeroDivisionError:
except ValueError:
print("Invalid value!")
try:
result = 10 / "a"
except Exception as e:
try:
result = 10 / 2
except ZeroDivisionError:
else:
finally:
def check_positive(number):
if number <= 0:
raise ValueError("The number is not positive")
return number
try:
check_positive(-10)
except ValueError as e:
print(e)
Syntax Errors: Occur when the Python parser detects an incorrect statement.
Exceptions: Occur during execution, disrupting the normal flow of the program.
Exception Handling: Use try, except, else, and finally blocks to handle exceptions
and ensure your program can deal with errors gracefully.