Cursor AI 으로 계산기를 만들어보았다.

 

 

 

커서란?

: 인공지능 기반 코드 에디터이다.

 

ChatGPT 와 Visual Studio 합쳐진 것으로 보면 된다.

코드 작성 중 나의 코드에 추가할 기능을 AI 프롬프트에 물어보면 필요한 기능을 추가해준다.

 

다운로드 링크

https://www.cursor.com/

 

설치

 

 

 

 

 

 

설치 후 Cursor 를 실행한다.

 

그 후 프로젝트 폴더를 지정하여 열어준다. 그러면 아래와 같은 화면이 된다.

 

 

Agent 의 claude-3.7-sonnect 를 선택한 후

계산기를 만들어달라고 요청해보았다.

 

 

cursor AI 가 만든 코드

 

calculator.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Division by zero"
    return x / y

def calculator():
    print("간단한 계산기 프로그램")
    print("수행할 연산을 선택하세요:")
    print("1. 덧셈")
    print("2. 뺄셈")
    print("3. 곱셈")
    print("4. 나눗셈")
    print("5. 종료")

    while True:
        # 사용자 입력 받기
        choice = input("선택 (1/2/3/4/5): ")

        # 종료 조건 확인
        if choice == '5':
            print("계산기를 종료합니다.")
            break

        # 유효한 선택인지 확인
        if choice not in ('1', '2', '3', '4'):
            print("잘못된 입력입니다. 다시 시도하세요.")
            continue

        # 숫자 입력 받기
        try:
            num1 = float(input("첫 번째 숫자를 입력하세요: "))
            num2 = float(input("두 번째 숫자를 입력하세요: "))
        except ValueError:
            print("유효한 숫자를 입력하세요.")
            continue

        # 선택에 따른 연산 수행
        if choice == '1':
            print(f"{num1} + {num2} = {add(num1, num2)}")
        elif choice == '2':
            print(f"{num1} - {num2} = {subtract(num1, num2)}")
        elif choice == '3':
            print(f"{num1} * {num2} = {multiply(num1, num2)}")
        elif choice == '4':
            result = divide(num1, num2)
            print(f"{num1} / {num2} = {result}")

# 프로그램 실행
if __name__ == "__main__":
    calculator()

 

 

gui_calculator.py

import tkinter as tk
from tkinter import messagebox

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("GUI 계산기")
        self.root.geometry("300x400")
        self.root.resizable(False, False)
        self.root.configure(bg="#f0f0f0")

        # 계산식을 저장할 변수
        self.current_expression = ""
        self.total_expression = ""

        # 디스플레이 프레임 생성
        self.display_frame = self.create_display_frame()

        # 결과 및 현재 계산식 레이블
        self.total_label, self.label = self.create_display_labels()

        # 숫자 및 연산자 버튼 배열 정의
        self.digits = {
            7: (1, 1), 8: (1, 2), 9: (1, 3),
            4: (2, 1), 5: (2, 2), 6: (2, 3),
            1: (3, 1), 2: (3, 2), 3: (3, 3),
            0: (4, 2), '.': (4, 1)
        }
        
        self.operations = {"/": "÷", "*": "×", "-": "-", "+": "+"}
        
        # 버튼 프레임 생성
        self.buttons_frame = self.create_buttons_frame()

        # 버튼 프레임 확장
        self.buttons_frame.rowconfigure(0, weight=1)
        for x in range(1, 5):
            self.buttons_frame.rowconfigure(x, weight=1)
            self.buttons_frame.columnconfigure(x, weight=1)
            
        # 숫자 버튼 생성
        self.create_digit_buttons()
        
        # 연산자 버튼 생성
        self.create_operator_buttons()
        
        # 특수 버튼 생성 (Clear, Equals)
        self.create_special_buttons()

    def create_display_frame(self):
        frame = tk.Frame(self.root, height=80, bg="#f8f8f8")
        frame.pack(expand=True, fill="both")
        return frame

    def create_display_labels(self):
        total_label = tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, 
                              bg="#f8f8f8", fg="#808080", padx=24, font=("Arial", 12))
        total_label.pack(expand=True, fill="both")
        
        label = tk.Label(self.display_frame, text=self.current_expression, anchor=tk.E, 
                        bg="#f8f8f8", fg="#000000", padx=24, font=("Arial", 20, "bold"))
        label.pack(expand=True, fill="both")
        
        return total_label, label

    def create_buttons_frame(self):
        frame = tk.Frame(self.root)
        frame.pack(expand=True, fill="both")
        return frame

    def add_to_expression(self, value):
        self.current_expression += str(value)
        self.update_label()

    def create_digit_buttons(self):
        for digit, grid_value in self.digits.items():
            button = tk.Button(self.buttons_frame, text=str(digit), bg="#ffffff", fg="#000000",
                              font=("Arial", 14), borderwidth=0,
                              command=lambda x=digit: self.add_to_expression(x))
            button.grid(row=grid_value[0], column=grid_value[1], sticky=tk.NSEW, padx=2, pady=2)

    def append_operator(self, operator):
        self.current_expression += operator
        self.total_expression += self.current_expression
        self.current_expression = ""
        self.update_total_label()
        self.update_label()

    def create_operator_buttons(self):
        i = 0
        for operator, symbol in self.operations.items():
            button = tk.Button(self.buttons_frame, text=symbol, bg="#f0f0f0", fg="#000000",
                              font=("Arial", 14), borderwidth=0,
                              command=lambda x=operator: self.append_operator(x))
            button.grid(row=i, column=4, sticky=tk.NSEW, padx=2, pady=2)
            i += 1

    def clear(self):
        self.current_expression = ""
        self.total_expression = ""
        self.update_label()
        self.update_total_label()

    def evaluate(self):
        self.total_expression += self.current_expression
        self.update_total_label()
        
        try:
            self.current_expression = str(eval(self.total_expression))
            self.total_expression = ""
        except Exception as e:
            self.current_expression = "Error"
            messagebox.showerror("오류", "유효하지 않은 계산식입니다.")
        finally:
            self.update_label()

    def create_special_buttons(self):
        self.create_clear_button()
        self.create_equals_button()

    def create_clear_button(self):
        button = tk.Button(self.buttons_frame, text="C", bg="#f0f0f0", fg="#000000",
                          font=("Arial", 14), borderwidth=0, command=self.clear)
        button.grid(row=0, column=1, sticky=tk.NSEW, padx=2, pady=2)

    def create_equals_button(self):
        button = tk.Button(self.buttons_frame, text="=", bg="#4285f4", fg="#ffffff",
                          font=("Arial", 14), borderwidth=0, command=self.evaluate)
        button.grid(row=4, column=3, columnspan=2, sticky=tk.NSEW, padx=2, pady=2)

    def update_total_label(self):
        expression = self.total_expression
        for operator, symbol in self.operations.items():
            expression = expression.replace(operator, f' {symbol} ')
        self.total_label.config(text=expression)

    def update_label(self):
        self.label.config(text=self.current_expression[:11])

def main():
    root = tk.Tk()
    calc = Calculator(root)
    root.mainloop()

if __name__ == "__main__":
    main()

 

 

README.md

# 파이썬 계산기 프로그램

이 프로젝트는 파이썬으로 구현된 두 가지 계산기 프로그램을 포함하고 있습니다:
1. 콘솔 기반 계산기 (`calculator.py`)
2. GUI 기반 계산기 (`gui_calculator.py`)

## 요구 사항

- Python 3.6 이상
- GUI 계산기를 위한 tkinter (대부분의 파이썬 설치에 기본 포함됨)

## 콘솔 기반 계산기 사용법

콘솔 기반 계산기를 실행하려면 다음 명령어를 사용하세요:

```
python calculator.py
```

프로그램이 실행되면:
1. 메뉴에서 원하는 연산을 선택합니다 (1-4).
2. 두 개의 숫자를 입력합니다.
3. 결과가 표시됩니다.
4. 종료하려면 '5'를 입력하세요.

## GUI 기반 계산기 사용법

GUI 계산기를 실행하려면 다음 명령어를 사용하세요:

```
python gui_calculator.py
```

GUI 계산기 기능:
- 숫자 버튼 (0-9)와 소수점(.)을 클릭하여 숫자를 입력합니다.
- 연산자 버튼(+, -, ×, ÷)을 클릭하여 연산을 선택합니다.
- '=' 버튼을 클릭하여 계산 결과를 확인합니다.
- 'C' 버튼을 클릭하여 입력을 초기화합니다.

## 기능

두 계산기 모두 다음 기본 연산을 지원합니다:
- 덧셈 (+)
- 뺄셈 (-)
- 곱셈 (*)
- 나눗셈 (/)

## 주의사항

- 나눗셈 시 0으로 나누려고 하면 오류 메시지가 표시됩니다.
- GUI 계산기에서는 복잡한 수식을 한 번에 계산할 수 있습니다.

 

실행 결과

 

 

cursor AI 는 공부용으로 괜찮은 것 같다.

 

무료/유료 버전이 있으며, 무료 버전으로도 충분히 가지고 놀 수 있어 한 번 사용해보는 것을 추천한다.