TIL | 파이썬으로 간단한 계산기 모듈 만들기

sik2·2021년 4월 2일

Python

목록 보기
5/5

파이썬으로 간단한 계산기 모듈을 만들어보자

먼저 작은 프로젝트진행에 있어 한번에 함수를 만들기보다는 최소기능 단위로 만들고 기능을 추가하는 방식으로 진행할 예정이다.

  • 먼저 calculator.py 파일을 만든다.
def plus(a="none",b="none"):
   if a=="none" or b=="none":
       print("수를 입력해주세요")
   else:
       a=int(a)
       b=int(b)
   return(a*b)

def minus(a="none",b="none"):
    if a=="none" or b=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
        b=int(b)
    return(a-b)

def times(a="none",b="none"):
    if a=="none" or b=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
        b=int(b)
    return(a*b)

def divison(a="none",b="none"):
    if a=="none" or b=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
        b=int(b)
    return(a/b)

def negation(a="none"):
    if a=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
    return(-a)

def power(a="none",b="none"):
    if a=="none" or b=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
        b=int(b)
    return(pow(a,b))

def remainder(a="none",b="none"):
    if a=="none" or b=="none":
        print("수를 입력해주세요")
    else:
        a=int(a)
        b=int(b)
    return(a%b)

이후 main.py 에서 import 해서 해당 모듈을 사용한다.

import calculator

plus(2,3);
minus(2,3);
  • try excepy 키워드를 활용한 예외 처리 버전
def cal_plus(a,b):
    try:
        return a+b
    except:
        return "ERROR"

def cal_minus(a,b):
    try:
        return a-b
    except:
        return "ERROR"

def cal_time(a,b):
    try:
        return a*b
    except:
        return "ERROR"

def cal_divd(a,b):
    try:
        return a/b
    except:
        return "ERROR"

def cal_neg(a):
    try:
        return -a
    except:
        return "ERROR"

def cal_power(a,b):
    try:
        return a ** b
    except:
        return "ERROR"

def cal_remainder(a,b):
    try:
        return a % b
    except:
        return "ERROR"

참고자료

https://ahnheejong.name/articles/becoming-better-programmer/

profile
기록

1개의 댓글

comment-user-thumbnail
2021년 9월 20일

다음 계산하는 것을 모듈로 만들고, 2개의 숫자와 계산할 연산을 입력받아 함수를 호출하여 처리하는 프로그램을 작성하시오.(단 빼기를 할 때는 큰수에서 작은 수를 빼도록하고 나누기를 할 때는 젯수가 0이면 젯수를 다시 입력 받도록하시오)
1. 합계계산
2. 빼기계산
3. 곱하기계산
4. 나누어 몫과 나머지가 따로 나오기

혹시 이것도 코드 짜주실 수 있나요?ㅜㅠ

답글 달기