[Python] ATM 프로그램/은행 프로그램 파이썬으로 만들기 (파일 입출력으로 데이터 저장)

2022. 11. 10. 17:04·Programming Languages/Python
728x90

 

Python 으로 간단한 콘솔 프로그램인 ATM 프로그램을 만들어 보았다 ! 

예전에는 C++ 으로 객체지향프로그래밍 수업에서 비슷한 은행 프로그램을 만든 적이 있었는데.. 그때보다는 확실히 파이썬으로 하니까 금방금방 만들어진다. 

간단하게 잔액 확인/deposit/withdraw 기능을 두고 설계했다. 
비밀번호 바꾸기 기능, 계좌번호 찾기 기능도 추가했다. 

class를 좀 잘 써서 예쁜 객체지향 프로그래밍을 하고 싶었으나, Account class 만든거 이외에 class를 활용을 안했다. 
개선한다면 Controller class 정도 만들어서 계좌 작업 처리 관련 함수들 (deposit, withdraw...) 을 묶을 수 있겠다. 

객체지향.. 말로는 쉬운데 직접 설계하면 아직도 쉽지가 않다 ㅋㅋ 오랜만에 코테가 아닌 간단한 과제를 해서 재미있었다 ㅎㅎ

https://github.com/freemjstudio/ATM_project_python

 

GitHub - freemjstudio/ATM_project_python: ATM Project - Minjee Woo

ATM Project - Minjee Woo . Contribute to freemjstudio/ATM_project_python development by creating an account on GitHub.

github.com

 

main.py 코드 

import random

account_object_list = []
FILE = "data.txt"

class Account:
    def __init__(self, account_number, name, balance, password, email):
        self.account_number = account_number
        self.name = name
        self.balance = balance
        self.password = password
        self.email = email

    def print_account(self):
        print("-------------- User Information --------------")
        print("  Name: ",self.name)
        print("  Account Number :", self.account_number)
        print("  Balance: $", self.balance)
        print("-----------------------------------------------")

    def get_account_info(self):
        return self.account_number, self.name, self.balance

    def check_password(self):
        print("Enter the PIN : ")
        input_password = input()
        if input_password == self.password:
            return True
        else:
            return False # 회원정보 불일치

# Function
def register(): # 회원 가입
    print("Enter name: ")
    input_name = input()
    print("Enter email number: ")
    input_email = input()
    print("Enter PIN: ")
    input_password = input()

    new_account_num = ""
    num1 = random.randint(0, 999)
    num2 = random.randint(0, 999999)
    num3 = random.randint(0, 99999)
    num1 = str(num1).zfill(3)
    num2 = str(num2).zfill(6)
    num3 = str(num3).zfill(5)
    new_account_num = num1+ '-' +num2+'-'+num3

    new_account = Account(new_account_num, input_name, 0, input_password, input_email) # balance = 0
    account_object_list.append(new_account)
    new_account.print_account()
    save_data()
    print("Successfully Registered! ")

def check_vaild_account(user_account):
    for account_object in account_object_list:
        new_account_number = account_object.account_number.replace('-','')
        if user_account == account_object.account_number:
            return account_object
        elif user_account == new_account_number:
            return account_object
    return None

def read_data():
    print("[Loading] System is reading the data...")
    try:
        file = open(FILE, 'r')
        while True:
            line = file.readline()
            if not line:
                break
            account_number, name, balance, password, email = line.split()
            account_object_list.append(Account(account_number, name, int(balance), password, email))
        file.close()
    except Exception as error:
        print("[Error] There's no data.txt file. ")
        print(error)

def save_data():
    f = open(FILE, 'w')
    for data in account_object_list:
        data_str = data.account_number+' '+data.name+' '+str(data.balance)+' '+data.password+' '+data.email+' \n'
        f.write(data_str)
    f.close()

def deposit(user_data):
    print("How much would you like to deposit? ")
    input_deposit = input()
    if input_deposit.isdigit():
        user_data.balance += int(input_deposit)
        user_data.print_account()
    else:
        print("[Error] Enter valid integer!")

def withdraw(user_data):
    print("How much would you like to withdraw? ")
    input_withdraw = input()
    if input_withdraw.isdigit():
        if user_data.balance >= int(input_withdraw):
            user_data.balance -= int(input_withdraw)
            user_data.print_account()
        else:
            print("[Error] Insufficient balance in your account! ")
    else:
        print("[Error] Enter valid integer!")

def check_valid_user(input_user, input_email):
    for account_object in account_object_list:
        if input_user == account_object.name and input_email == account_object.email:
            return account_object
    return None

def find_account_number():
    print("Enter user name:")
    input_name = input()
    print("Enter user email:")
    input_email = input()
    account_object = check_valid_user(input_name, input_email)
    if account_object != None:
        print(input_name,"'s account number is")
        print(account_object.account_number)
        print("Thank you")
    else:
        print("[Error] There's no user information")
    return None

def change_password():
    print("Enter account")
    input_account = input()
    print("Enter user name")
    input_name = input()
    print("Enter user email")
    input_email = input()
    account_object = check_vaild_account(input_account)
    account_object2 = check_valid_user(input_name, input_email)
    if account_object2 != None and account_object != None:
        while True:
            print("Enter new PIN:")
            input_password = input()
            print("Enter the new PIN number again:")
            input_password_check = input()

            if input_password_check == input_password:
                account_object.password = input_password
                save_data()
                print("PIN number is successfully changed")
                break
            else:
                print("[Error] PIN number doesn't match ! ")
    else:
        print("[Error] There's no user matched with the input data ! ")
        return

# View
def default_view():
    thank_you_ascii = """
              ________                __                       
         /_  __/ /_  ____ _____  / /__   __  ______  __  __
          / / / __ \/ __ `/ __ \/ //_/  / / / / __ \/ / / /
         / / / / / / /_/ / / / / ,<    / /_/ / /_/ / /_/ / 
        /_/ /_/ /_/\__,_/_/ /_/_/|_|   \__, /\____/\__,_/  
                                      /____/               
            
            Developed by Minjee woo @freemjstudio GitHub
            """
    read_data()
    while True:
        print("--------------- ATM Service ---------------")
        print(" 1. Enter Account")  # 계좌번호 입력하기
        print(" 2. Register ")  # 회원가입
        print(" 3. Find Account")
        print(" 4. Can't find PIN number")
        print(" 0. Exit")
        print("Choose the option: ", end=" ")
        op = input()
        if op == '1':
            print("Enter the account number")
            user_input_account = input()
            user_data = check_vaild_account(user_input_account)

            if user_data != None:
                if user_data.check_password():
                    menu_view(user_data)
                else:
                    print("[Error] Wrong PIN number")
            else:
                print("[Error] Wrong Account number")
        elif op == '2':
            register()
        elif op == '3':
            find_account_number()
        elif op == '4':
            change_password()
        elif op == '0':
            save_data()
            print(thank_you_ascii)
            exit()
        else:
            print("[Error] Enter right number")

def menu_view(user_data):
    print("--------------- MENU ----------------")
    print("| 1. Check balance                  |")
    print("| 2. Deposit                        |")
    print("| 3. Withdraw                       |")
    print("| 0. Exit                           |")
    print("-------------------------------------")
    print("Choose the option")
    op = input()
    if op == '0':
        return  # 이전 화면으로 돌아가기
    elif op == '1':  # Check balance
        user_data.print_account()
    elif op == '2':  # Deposit
        deposit(user_data)
    elif op == '3':
        withdraw(user_data)

def main():
    atm_ascii = """ 
    ___  ________  ___   _____                 _         
   /   |/_  __/  |/  /  / ___/___  ______   __(_)_______ 
  / /| | / / / /|_/ /   \__ \/ _ \/ ___/ | / / / ___/ _ \ 
 / ___ |/ / / /  / /   ___/ /  __/ /   | |/ / / /__/  __/
/_/  |_/_/ /_/  /_/   /____/\___/_/    |___/_/\___/\___/ 
                                                         
  Developed by Minjee woo, GitHub @freemjstudio 
  
    """
    print(atm_ascii)
    default_view()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    main()

 

단, 코드를 실행할 때 data.txt 파일과 main.py 파일을 같은 위치의 directory에 두어야 합니다 !! 

질문/더 나은 코드 환영합니당

728x90

'Programming Languages > Python' 카테고리의 다른 글

[Python] 2차원 배열 90도 회전하기 (시계방향)  (0) 2023.01.13
[백준] 17281번: 야구 (Python/파이썬)  (0) 2022.12.24
Python k 진수로 바꾸기  (0) 2022.09.30
python re.sub - 정규화표현식으로 문자열 바꿔주기  (1) 2022.09.11
[Python] defaultdict 문법 정리  (0) 2022.09.11
'Programming Languages/Python' 카테고리의 다른 글
  • [Python] 2차원 배열 90도 회전하기 (시계방향)
  • [백준] 17281번: 야구 (Python/파이썬)
  • Python k 진수로 바꾸기
  • python re.sub - 정규화표현식으로 문자열 바꿔주기
minjiwoo
minjiwoo
Data Engineering과 Cloud Native 기술에 대해 Dive Deep 하는 플랫폼 엔지니어가 되는 것을 목표로 하고 있습니다. 경험과 공부한 내용을 기록하며 지속가능한 엔지니어가 되는 것이 꿈입니다.
minjiwoo
minji's engineering note
minjiwoo
전체
오늘
어제
  • 분류 전체보기 (613)
    • Data Engineering (42)
      • Apache Spark (11)
      • Databricks & Delta Lake (9)
      • Airflow (3)
      • SQL (6)
      • Trouble Shooting (2)
      • Hadoop (2)
      • MLOps (1)
    • Cloud Engineering (104)
      • AWS (23)
      • Linux 🐧 (29)
      • Docker 🐳 (21)
      • Kubernetes ⚙️ (20)
      • Ansible (10)
    • Computer Science (87)
      • 네트워크 (9)
      • 운영체제 (25)
      • 정보처리기사 (48)
      • CS 기술 면접 스터디 (3)
    • Programming Languages (27)
      • Python (17)
      • C와 C++ (10)
    • Backend (5)
      • Django (2)
    • 프로젝트 (2)
      • 테크포임팩트 (2)
    • iOS (11)
      • 레이블러리 (2)
    • Algorithm (PS) (275)
      • LeetCode (6)
    • 개발일기 (30)
      • 내돈내산 후기🎮 (3)
      • 개발자 취준생 (5)
      • Today I Learned (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Hi there

인기 글

태그

  • Swift
  • 쿠버네티스
  • Leetcode
  • 데이터브릭스
  • SPARK
  • 리눅스
  • Databricks
  • docker
  • 백트래킹
  • Kubernetes
  • linux
  • EC2
  • dp
  • 데이터엔지니어링
  • 코딩테스트
  • 데이터엔지니어
  • 스파크
  • 클라우드
  • 백준
  • BFS
  • 파이썬
  • dfs
  • 알고리즘
  • python
  • 카카오코딩테스트
  • ansible
  • 프로그래머스
  • AWS
  • 운영체제
  • 빅데이터

최근 댓글

최근 글

hELLO· Designed By정상우.v4.5.2
minjiwoo
[Python] ATM 프로그램/은행 프로그램 파이썬으로 만들기 (파일 입출력으로 데이터 저장)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.