Day 30 - 错误、异常与 JSON 数据 - Python学习笔记

Udemy - 100 Days of Code: The Complete Python Pro Bootcamp

Day 30 - Errors, Exceptions and JSON Data

目录

        • [228. Catch Exceptions](#228. Catch Exceptions)
        • [229. Raise Exceptions](#229. Raise Exceptions)
        • [230. Improve the NATO Alphabet Project](#230. Improve the NATO Alphabet Project)
        • [231. Read and Write JSON Data](#231. Read and Write JSON Data)
        • [232. Improve the Password Manager Project](#232. Improve the Password Manager Project)
228. Catch Exceptions

try:Something that might cause an exception 可能引发异常的代码
except:Do this if there was an exception 发生异常时执行的代码
else:Do this if there were no exceptions 没有异常时执行的代码
finally:Do this no matter what happens 不管有没有异常都会执行的代码

python 复制代码
try:  
    file = open("file.txt", "r", encoding="utf-8")  
    content = file.read()  
except FileNotFoundError:
    print("File was not found, creating a new file.")
    file = open("file.txt", "w", encoding="gbk")  
    file.write("你好")  
except UnicodeDecodeError as e:  
    print(f"Encoding error: {e}")  
else:  
    print(f"File content: {content}")  
finally: 
    print("File was closed.")
    file.close()   
229. Raise Exceptions
python 复制代码
height = float(input("Height (m): "))  
weight = float(input("Weight (kg): "))  
  
if height > 3:  
    raise ValueError("Human Height should not be over 3 meters.")  
  
bmi = weight / height ** 2  
print(bmi)
230. Improve the NATO Alphabet Project

NATO Alphabet Project

python 复制代码
import pandas  
  
df = pandas.read_csv("nato_phonetic_alphabet.csv")  
phonetic_dict = {row.letter: row.code for index, row in df.iterrows()}  
print(phonetic_dict)  
  
def generate_alphabet():  
    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_alphabet()  
    else:  
        print(output_list)  

generate_alphabet()
231. Read and Write JSON Data

Python JSON Module

python 复制代码
import json        # JavaScript Object Notation  JavaScript对象表示法

# Read JSON Data (JSON String -> Python Object)  
json_str = '{"name":"John", "age":30, "city":"New York"}'  
data = json.loads(json_str)  
print(data)  

# Write JSON Data (Python Object -> JSON String)  
data = {  
  "name": "John",  
  "age": 30,  
  "city": "New York"  
}  
json_str = json.dumps(data, indent=4)  
print(json_str) 

# Read JSON Data (JSON File -> Python Object)  
with open("data.json") as file:  
  data = json.load(file)  
print(data)

# Write JSON Data (Python Object -> JSON File)  
data = {  
  "name": "John",  
  "age": 30,  
  "city": "New York"  
}  
with open("data.json", mode="w") as file:  
    json.dump(data, file, indent=4)  
232. Improve the Password Manager Project

Password Manager Project

python 复制代码
from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
import pyperclip
import json


def generate_password():
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
    
    password_letters = [choice(letters) for _ in range(randint(8, 10))]
    password_symbols = [choice(symbols) for _ in range(randint(2, 4))]
    password_numbers = [choice(numbers) for _ in range(randint(2, 4))]
    
    password_list = password_letters + password_symbols + password_numbers
    shuffle(password_list)
    
    password = "".join(password_list)
    password_entry.delete(0, END)
    password_entry.insert(0, password)
    pyperclip.copy(password)


def save():
    website = website_entry.get()
    email = email_entry.get()
    password = password_entry.get()
    new_data = {
        website: {
            "email": email,
            "password": password,
        }
    }
    
    if len(website) == 0 or len(email) == 0 or len(password) == 0:
        messagebox.showinfo(
            title="Oops",
            message="Please make sure you haven't left any fields empty."
        )
    else:
        try:
            with open("data.json", "r") as data_file:
                data = json.load(data_file)
        except FileNotFoundError:
            with open("data.json", "w") as data_file:
                json.dump(new_data, data_file, indent=4)
        else:
            data.update(new_data)
            with open("data.json", "w") as data_file:
                json.dump(data, data_file, indent=4)
        finally:
            website_entry.delete(0, END)
            password_entry.delete(0, END)


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.")


# UI SETUP
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)

canvas = Canvas(width=200, height=200)
logo_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=logo_img)
canvas.grid(column=0, row=0, columnspan=3)

# Labels
website_label = Label(text="Website:")
website_label.grid(column=0, row=1)
email_label = Label(text="Email/Username:")
email_label.grid(column=0, row=2)
password_label = Label(text="Password:")
password_label.grid(column=0, row=3)

# Entries
website_entry = Entry(width=20)
website_entry.grid(column=1, row=1)
website_entry.focus()
email_entry = Entry(width=38)
email_entry.grid(column=1, row=2, columnspan=2)
email_entry.insert(0, "angela@gmail.com")
password_entry = Entry(width=20)
password_entry.grid(column=1, row=3)

# Buttons
search_button = Button(text="Search", width=16, command=find_password)
search_button.grid(row=1, column=2)
generate_button = Button(text="Generate Password", width=16, command=generate_password)
generate_button.grid(column=2, row=3)
add_button = Button(text="Add", width=38, command=save)
add_button.grid(column=1, row=4, columnspan=2)

window.mainloop()
相关推荐
朝朝辞暮i3 小时前
VLA 系统学习第 4 课:一个 Batch 进入神经网络后,模型到底是怎么“学会”的?
人工智能·python·神经网络·vla
Ada's3 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
2601_962885724 小时前
如何用 Python 计算 TRIX 三重指数平滑均线指标?
开发语言·python
还卿一钵无情泪4 小时前
Unsloth 微调 构建自己的大模型 没有GPU也能微调
linux·开发语言·人工智能·python·大模型·nlp·unsloth
蜗牛互联网7 小时前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
statistican_ABin7 小时前
中国国际旅游发展分析报告—基于世界银行国际旅游数据的多维度分析
python·机器学习·旅游
青少儿编程课堂7 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
code2cat7 小时前
【随笔】MCP工具注解的信任边界:四个提示如何参与调用决策
python·ai agent·mcp
慢云智慧空间8 小时前
从设备智能到空间理解,慢云科技如何重新定义智慧建筑
python·科技
浮链序8 小时前
用 Claude Haiku 5.5 做子智能体路由,把 Agent 成本砍掉六成
人工智能·python·llm