# FileNotFound
with open("a_file.txt") as file:
file.read()
# KeyError
a_dictionary = {"key": "value"}
value = a_dictionary["non_existent_key"]
# IndexError
fruit_list = ["Apple", "Banana", "Pear"]
fruit = fruit_list[3]
# TypeError
text = "abc"
print(text + 5)
In programming, what we can do is we can catch these exceptions. When something goes wrong and in that moment we catch that exception, then it doesn't have to fail catastrophically.
The code looks like when we're dealing with these exceptions.
try
: Something that might caught an exception.
except
: Do this if there was an exception.
else
: Do this of there were no exceptions.
finally
: Do this no matter what happens.
try:
file = open("a_file.txt")
a_dictionary = {"key": "value"}
print(a_dictionary["sdfsdf"])
except FileNotFoundError:
file = open("a_file.txt", "w")
file.write("Something")
except KeyError as error_message:
print(f"The key {error_message} does not exist.")
#output
The key 'sdfsdf' does not exist.
try:
file = open("a_file.txt")
a_dictionary = {"key": "value"}
print(a_dictionary["key"])
except FileNotFoundError:
file = open("a_file.txt", "w")
file.write("Something")
except KeyError as error_message:
print(f"The key {error_message} does not exist.")
else:
content = file.read()
print(content)
finally:
file.close()
print("File was closed.")
#output
value
Something
File was closed.
raise
#BMI Example
height = float(input("Height: "))
weight = int(input("Weight: "))
if height > 3:
raise ValueError("Human Height should not be over 3 meters.")
bmi = weight / height ** 2
print(bmi)
#input
Height: 325
Weight: 56
#output
Traceback (most recent call last):
File "main.py", line 24, in module
raise ValueError("Human Height should not be over 3 meters.")
ValueError: Human Height should not be over 3 meters.
fruits = ["Apple", "Pear", "Orange"]
def make_pie(index):
try:
fruit = fruits[index]
except IndexError:
print("Fruit pie")
else:
print(fruit + " pie")
make_pie(4)
facebook_posts = [
{'Likes': 21, 'Comments': 2},
{'Likes': 13, 'Comments': 2, 'Shares': 1},
{'Likes': 33, 'Comments': 8, 'Shares': 3},
{'Comments': 4, 'Shares': 2},
{'Comments': 1, 'Shares': 1},
{'Likes': 19, 'Comments': 3}
]
total_likes = 0
for post in facebook_posts:
try:
total_likes = total_likes + post['Likes']
except KeyError:
pass
print(total_likes)
#output
86
in the NATO Phonetic Project
import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv")
phonetic_dict = {row.letter: row.code for (index, row) in data.iterrows()}
print(phonetic_dict)
def generate_phonetic():
word = input("Enter a word: ").upper()
try:
output_list = [phonetic_dict[letter] for letter in word]
except KeyError:
print("Sorry, only letters in the alphabet please.")
generate_phonetic()
else:
print(output_list)
generate_phonetic()
JSON (JavaScript Object Notation) is a lightweight data interchange format inspired by JavaScript object literal syntax.
Write : json.dump()
Read : json.load()
Update: json.update()
in the password manager
import json
website = website_entry.get()
email = email_entry.get()
password = password_entry.get()
new_data = {
website: {
"email": email,
"password": password
}
}
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
# Updating old data with new data
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
data.json
생성 전:
try:
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
# Updating old data with new data
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
finally:
website_entry.delete(0, END)
password_entry.delete(0, END)
Search Button
# ---------------------------- FIND PASSWORD ------------------------------- #
def find_password():
website = website_entry.get()
try:
with open("data.json") as data_file:
data = json.load(data_file)
except FileNotFoundError:
messagebox.showinfo(title="Error", message="No Data File Found.")
else:
if website in data:
email = data[website]["email"]
password = data[website]["password"]
messagebox.showinfo(title=website, message=f"Email: {email}\nPassword: {password}")
else:
messagebox.showinfo(title="Error", message=f"No details for {website} exists.")
# We could create an exception here.
# But the thing I want to keep in mind is
# that if I can do somethind with if and else very easily,
# then we should stick to if and else.
# Buttons
search_button = Button(text="Search", width=14, command=find_password)
search_button.grid(column=2, row=1)