728x90
반응형
사칙연산기 (CLI) 간단 구현하기

다음을 참고:
2024.07.24 - [Python] - [Python] 사용자와 상호작용: 입력받기: input, sys.argv and argparse
[Python] 사용자와 상호작용: 입력받기: input, sys.argv and argparse
input() 함수 사용하기2023.10.10 - [Python] - [Python] input 함수 사용하여 사용자 입력받기. [Python] input 함수 사용하여 사용자 입력받기.Python의 input() 함수는표준 입력 스트림(stdin)으로부터 데이터를 입
ds31x.tistory.com
간단한 구현:
❯ python hw.py
Enter operation (+,-,*,/) : +
a = 3
b = 4
addition: 3.0 + 4.0 = 7.0
❯ python hw.py + 3 4
addition: 3.0 + 4.0 = 7.0
인자를 넘겨주지 않은 경우는 interactive mode로 동작하여 input()을 통해 입력을 받고,
인자를 넘겨받은 경우는 op a b 의 형태로 받아서 이를 통해 연산을 수행.
import sys
def add(a,b):
tmp = a+b
print(f"addition: {a} + {b} = {tmp}")
def subtract(a,b):
tmp = a-b
print(f"subtraction: {a} - {b} = {tmp}")
def multiply(a,b):
tmp = a*b
print(f"multiplication: {a} * {b} = {tmp}")
def divide(a,b):
tmp = a/b
print(f"division: {a} / {b} = {tmp}")
def main():
params = sys.argv
# print(len(params))
if len(params) == 1:
op = input("Enter operation (+,-,*,/) : ")
op = op.strip()
if op not in ["+", "-", "*", "/"]:
print(f"[{op}] is not supported! select op among (+,-,*,/)! ")
sys.exit(1)
a = float(input ("a = ").strip())
b = float(input ("b = ").strip())
elif len(params) == 4:
op = params[1]
if op not in ["+", "-", "*", "/"]:
print(f"[{op}] is not supported! select op among (+,-,*,/)! ")
sys.exit(1)
a = float(params[2])
b = float(params[3])
else:
print(f"[ERROR] not supported!:{params}")
match op:
case "+":
add(a,b)
case "-":
subtract(a,b)
case "*":
multiply(a,b)
case "/":
divide(a,b)
if __name__ == "__main__":
main()
다른 형태 구현:
소수점 precision등에 대한 구현을 해 본 구현물 (sys.argv 만 이용)
❯ python week02/ex/sysargv_cal.py --precision 2 add 3.2 5.1
3.20 + 5.10 = 8.30
코드는 다음과 같음:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
sysargv_cal.py - sys.argv만 사용한 간단 사칙연산기
기능:
- 전역 옵션:
--precision N : 소수점 자리수 지정
--int : 정수로 출력 (int(), precision 무시)
- 연산(op):
add, sub, mul, div, neg
- 위치 인자:
x (항상), y (neg 제외 시 필요)
"""
import sys
def rformat(is_int, precision, value):
"""전역 옵션에 따라 숫자를 문자열로 변환."""
if is_int:
return str(int(value))
if precision is not None:
return f"{value:.{precision}f}"
return f"{value:.6f}"
def main():
argv = sys.argv[1:] # 스크립트 파일명 은 제외
# 옵션 파싱
precision = None
is_int = False
positional = [] # 위치 인자 (연산자, 숫자들)
i = 0
while i < len(argv):
if argv[i] == "--precision":
if i + 1 >= len(argv):
print("에러: --precision 뒤에 숫자를 지정해야 합니다.", file=sys.stderr)
sys.exit(2)
try:
precision = int(argv[i + 1])
except ValueError:
print("에러: --precision 값은 정수여야 합니다.", file=sys.stderr)
sys.exit(2)
i += 2
elif argv[i] == "--int":
is_int = True
i += 1
else:
positional.append(argv[i])
i += 1
# 최소 요구: 연산자와 첫 번째 숫자
if len(positional) < 2:
print("사용법: sysargv_cal.py [--precision N|--int] op x [y]", file=sys.stderr)
sys.exit(2)
op = positional[0]
try:
x = float(positional[1])
except ValueError:
print("에러: x는 숫자여야 합니다.", file=sys.stderr)
sys.exit(2)
y = None
if op != "neg":
if len(positional) < 3:
print(f"에러: 연산 '{op}'에는 두 번째 숫자 y가 필요합니다.", file=sys.stderr)
sys.exit(2)
try:
y = float(positional[2])
except ValueError:
print("에러: y는 숫자여야 합니다.", file=sys.stderr)
sys.exit(2)
# 연산 수행 및 출력
if op == "add":
result = x + y
print(f"{rformat(is_int, precision, x)} + {rformat(is_int, precision, y)} = {rformat(is_int, precision, result)}")
elif op == "sub":
result = x - y
print(f"{rformat(is_int, precision, x)} - {rformat(is_int, precision, y)} = {rformat(is_int, precision, result)}")
elif op == "mul":
result = x * y
print(f"{rformat(is_int, precision, x)} * {rformat(is_int, precision, y)} = {rformat(is_int, precision, result)}")
elif op == "div":
if y == 0:
print("0으로 나눌 수 없습니다.", file=sys.stderr)
sys.exit(1)
result = x / y
print(f"{rformat(is_int, precision, x)} / {rformat(is_int, precision, y)} = {rformat(is_int, precision, result)}")
elif op == "neg":
result = -x
print(f"-({rformat(is_int, precision, x)}) = {rformat(is_int, precision, result)}")
else:
print(f"알 수 없는 연산: {op}", file=sys.stderr)
sys.exit(2)
if __name__ == "__main__":
main()
같이보면 좋은 자료들
비슷한 예이나, interactive mode로만 동작하는 경우: 2024.11.13 - [Python] - [Py] 사칙연산 구현 예제
[Py] 사칙연산 구현 예제
문제Python 모듈을 작성하여 두 개의 숫자를 입력받아 사칙연산 결과를 출력하는 프로그램을 구현할 것.모듈의 설계 및 기능 요구 사항:두 숫자에 대한 사칙연산(덧셈, 뺄셈, 곱셈, 나눗셈)을 수행
ds31x.tistory.com
728x90
'Python' 카테고리의 다른 글
| random 모듈 사용법 (0) | 2025.10.02 |
|---|---|
| Isolation Forest : (0) | 2025.09.17 |
| [requests] Python의 requests 라이브러리 사용법. (2) | 2025.08.29 |
| [urllib] request 모듈 (1) | 2025.08.28 |
| Exceptions and Debugging Tools (1) | 2025.08.18 |