我用 Python 构建了一个有趣且实用的 ATM(它教会了我超出预期的东西 💳🐍)

发布: (2025年12月16日 GMT+8 18:08)
3 min read
原文: Dev.to

Source: Dev.to

为《我用 Python 构建了一个有趣的功能性 ATM(它教会了我超出预期的东西 💳🐍)》的封面图片

🏧 我们的 Python ATM 能做什么

  • ✅ PIN 认证
  • ✅ 查询余额
  • ✅ 取现
  • ✅ 存款
  • ✅ 简洁的菜单驱动流程
  • ✅ 错误处理(不允许负数取款)

全部使用纯 Python,无需外部库。

🎭 把 ATM 想象成守门人

ATM 并不在乎你是谁,只在乎规则:

  • PIN 正确吗?
  • 余额足够吗?
  • 金额合法吗?

我们的 Python ATM 也遵循同样的逻辑。

🧠 步骤 1:大脑(账户数据)

account = {
    "pin": "1234",
    "balance": 5000
}

🔐 步骤 2:PIN 认证(门卫)

def authenticate():
    pin = input("Enter your PIN: ")
    if pin == account["pin"]:
        print("✅ Access Granted\n")
        return True
    else:
        print("❌ Incorrect PIN")
        return False

没有正确的 PIN 就没有派对。

💰 步骤 3:查询余额

def check_balance():
    print(f"💳 Your current balance is: Rs {account['balance']}")

💸 步骤 4:取款(有规则!)

def withdraw():
    amount = int(input("Enter amount to withdraw: "))
    if amount  account["balance"]:
        print("❌ Insufficient balance")
    else:
        account["balance"] -= amount
        print(f"✅ Withdrawal successful! New balance: Rs {account['balance']}")

不允许透支。没有戏剧性。

💵 步骤 5:存款

def deposit():
    amount = int(input("Enter amount to deposit: "))
    if amount <= 0:
        print("⚠️ Invalid amount")
    else:
        account["balance"] += amount
        print(f"✅ Deposit successful! New balance: Rs {account['balance']}")

最佳功能——钱会进来 😄

🧭 步骤 6:ATM 菜单(魔法发生的地方)

def atm_menu():
    while True:
        print("\n🏧 ATM MENU")
        print("1. Check Balance")
        print("2. Withdraw Money")
        print("3. Deposit Money")
        print("4. Exit")
        choice = input("Choose an option: ")

        if choice == "1":
            check_balance()
        elif choice == "2":
            withdraw()
        elif choice == "3":
            deposit()
        elif choice == "4":
            print("👋 Thank you for using the ATM")
            break
        else:
            print("⚠️ Invalid choice")

循环让 ATM 持续运行,直到用户离开。

🚀 步骤 7:运行 ATM

if authenticate():
    atm_menu()

就这样——一个基于逻辑而非魔法的工作 ATM。

🎯 这个小 ATM 能教会你什么

  • 函数与模块化设计
  • 输入验证
  • 状态管理
  • 安全基础
  • 用户体验逻辑

这些正是银行应用、支付系统和后端服务使用的相同原则。

🧪 想要升级吗?

  • 多用户
  • PIN 重试次数限制
  • 交易历史
  • 基于文件的存储
  • GUI 或网页界面

每一次升级都让你更接近真实的应用开发。

🧠 最后思考

构建像这样的“小而有趣”的项目并不是“玩具编码”。这正是实际开发者学习思考的方式。如果你能构建一个 ATM,你就能构建任何东西。

祝编码愉快 🐍💻

Back to Blog

相关文章

阅读更多 »