01Write and read a file
main.py
with open("note.txt", "w") as f:
f.write("hello\nworld\n")
with open("note.txt") as f:
print(f.read())Output
hello world
Reading, writing, and exception handling.
with open("note.txt", "w") as f:
f.write("hello\nworld\n")
with open("note.txt") as f:
print(f.read())hello world
try:
n = int("abc")
except ValueError as e:
print("Caught:", e)Caught: invalid literal for int() with base 10: 'abc'
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")Cannot divide by zero Done
def sqrt(n):
if n < 0:
raise ValueError("n must be >= 0")
return n ** 0.5
try:
sqrt(-1)
except ValueError as e:
print(e)n must be >= 0