로컬 개발 환경 설정

JOOYEUN SEO·2024년 8월 20일

100 Days of Python

목록 보기
15/76
post-thumbnail

IDE(Integrated Development Environment), 통합 개발 환경

  • 코드 작성을 돕는 소프트웨어
  • 작성한 코드를 분석하고 오류를 찾음
  • 올바른 문체로 코드를 작성하도록 유도
  • 디버깅을 도움

❖ 파이참(pycharm)

파이썬에 특화된 IDE
(여태까지 사용한 replit처럼 간단한 텍스트 편집기로는 부족하기 때문에 앞으로 파이참으로 진행)

◇ 파이참 다운로드 순서

  1. 최신 버전의 python 다운 후 설치
    a. Add Python 현재버전 to PATH 체크
    b. Disable path length limit 클릭 후 승인
    c. 맥북 터미널에서 사용 가능한 명령어
    • 현재 설치된 버전 확인 :
      python -V, python --version
    • 현재 설치된 경로 확인 :
      which python
  2. 파이참 다운로드
    (무료 버전인 커뮤니티 다운)
  3. 파이참 설치 후 실행 → new project
    a. 폴더 선택
    b. Vase interpreter에서 최신 버전의 파이썬으로 설정
    c. 생성 후 폴더를 우클릭 → new → 새 file 추가
    d. main.py 파일 생성 후 코드 작성
    e. run으로 실행
    f. 콘솔창 마지막에 Process finished with exit code 0 가 뜨면 성공

◇ 파이참 단축키(MAC)

shortcutaction
Double ⇧ShiftQuickly find any file, action, class, symbol, tool window, or
setting in PyCharm, in your project, and in the current Git repository.
⌘Сmd + ⇧Shift + AFind a command and execute it, open a tool window, or search for a setting
⌥Opt + ↩EnterQuick-fixes for highlighted errors and warnings,
intention actions for improving and optimizing your code.
F2
⇧Shift + F2
Jump to the next highlighted error
Jump to the previous highlighted error
⌘Сmd + ESelect a recently opened file from the list
⌥Opt +
⌥Opt +
Extend selection
Shrink selection
⌘Сmd + /
⌘Сmd + ⌥Opt + /
Add/remove line or block comment
Comment out a line or block of code
⌥Opt + F7Find Usages
Show all places where a code element is used across your project
⌥Opt + ⇧Shift + dragMultiple cursors(select ranges by dragging)

◇ 파이참의 유용한 기능

  • 코드 맞춤법 검사
    • 작성한 영어 단어의 스펠링과 문법 검사
    • 스펠링이 틀렸을 경우, 체크해보라는 권고가 뜸
  • 넓은 개발 공간
    • 여러 개의 파일을 한 화면에서 함께 볼 수 있음
    • 파일 우클릭 → Split and Move Right/Down
  • 린터(linter) 내장
    • 먼지를 떼는 돌돌이 테이프처럼 지정된 코딩 스타일에 맞지 않는 코드를 골라내는 역할
    • 파이썬 개발자 대부분이 준수하는 스타일 가이드 PEP8를 자동으로 적용하고 린트
      • 들여쓰기 규칙
      • 한 줄의 최대길이
      • 개체들 사이에 들어가야 하는 빈 줄의 개수
        ...(규칙이 너무 많아서 전부 외우기는 불가능)
  • 로컬 히스토리
    • 지난 12시간 동안 코딩한 기록을 모두 볼 수 있음
    • 화면 아무곳이나 우클릭 → Local HistoryShow History
  • 스트럭쳐
    • 작성한 코드의 모든 변수와 함수가 분류됨
    • 화면 왼쪽 면에서 Structure 클릭 → 원하는 개체의 위치로 바로 이동, 편집 가능
  • 변수/함수 이름 일괄변경
    • 이름을 변경해야 하는데, 이전 이름이 이미 코드 여기저기에서 쓰였을 경우 유용한 기능
    • 해당 이름이 문자열 안에 있을 경우 인식하지 않기 때문에, 검색 후 바꾸는 것보다 편리
    • 변수/함수 이름 우클릭 → RefactorRenameDo Refactor
  • 이름 일괄변경
    • 문자열까지 검색하여 한 번에 수정 가능
    • EditFindReplace
    • Find : 변경하려는 단어 입력
    • Replace : 새로운 단어 입력
  • TODO 추적기
    • 작성 규칙 : # TODO 내용 작성, # TODO 내용 작성,...
    • 할 일이 여러 군데에 흩어져 있고 많을 때 편리텍스트한 기능
    • 순서가 뒤바뀌거나 여기저기 흩어져 있어도 아래쪽 TODO 탭에서 모두 확인 가능
      (클릭하면 작성된 위치로 바로 이동)

🗂️ Day15 프로젝트 : 커피 머신

🔍 유의 사항

  • 구현할 기능
    • 에스프레소, 라떼, 카푸치노를 만들어야 함 → 딕셔너리에 메뉴 정보 저장됨
      • Espresso($1.50) : 50ml water, 18g coffee
      • Latte($2.50) : 200ml water, 24g coffee, 150ml milk
      • Cappuchino($3.00) : 250ml water, 24g coffee, 100ml milk
    • 커피 자판기에 물 300ml, 우유 200ml, 커피 원두 100g을 채워야 함
    • 미국 동전을 넣어서 사용
      • Penny : 1 cent → $0.01
      • Nickel : 5 cents → $0.05
      • Dime : 10 cents → $0.10
      • Quater : 25 cents → $0.25
  • 요구 사항
    1. 머신 조작(입력창에 키워드 입력)
      → 동작이 끝난 후, 다음 고객을 위해 입력창이 다시 떠야 함
    • report : 현재 머신에 남은 재고와 쌓인 금액에 대한 리포트 출력
    • 커피 이름 : 커피 주문
    • off : 머신 끄기(코드 종료)
    1. 커피를 주문하면 남은 재료의 양을 파악 후 해당 커피의 레시피와 대조하여 확인
    • 재료가 충분하면, 돈을 받는 단계로 넘어감
    • 재료가 부족하면, 어떤 재료가 부족해서 커피를 만들 수 없는지 피드백
    1. 동전 처리
    • 동전을 종류별로 몇 개씩 넣는지 차례로 확인 후, 총 금액 계산
    1. 거래 과정이 정상적인지 판단
    • 돈을 적게 넣었을 경우, 넣은 돈을 전부 반환하고 주문 중단
    • 돈을 충분히 넣었을 경우, 보고서에 커피 값이 반영되고 주문 진행
      • 만약 커피 값보다 많은 돈이 들어왔으면, 거스름돈 반환
      • 거스름돈은 소수점 둘째자리까지 반올림
    1. 커피 제작
    • 커피를 성공적으로 제작하면 남은 재고도 수정되어야 함
    • 커피 이모지(☕)와 함께 주문한 커피가 준비되었음을 알리는 문구를 출력하며 종료

⌨️ 작성한 코드

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}
profit = 0

def report(save):
    print(f"Water: {resources["water"]}ml")
    print(f"Milk: {resources["milk"]}ml")
    print(f"Coffee: {resources["coffee"]}g")
    print(f"money: ${save}")


def check_amount(order):
    amount_water = True
    amount_milk = True
    amount_coffee = True
    if MENU[order]["ingredients"]["water"] > resources["water"]:
        print("Sorry there is not enough water.")
        amount_water = False
    if order != "espresso":
        if MENU[order]["ingredients"]["milk"] > resources["milk"]:
            print("Sorry there is not enough milk.")
            amount_milk = False
    if MENU[order]["ingredients"]["coffee"] > resources["coffee"]:
        print("Sorry there is not enough coffee.")
        amount_coffee = False
    if amount_water is True and amount_milk is True and amount_coffee is True:
        return 'yes'
    else:
        return 'no'


def coin_count(order):
    print("please insert coins.")
    quarter = float(input("How many quarters?: "))
    dime = float(input("How many dimes?: "))
    nickle = float(input("How many nickles?: "))
    penny = float(input("How many pennies?: "))
    total = round((quarter * 0.25) + (dime * 0.10) + (nickle * 0.05) + (penny * 0.01), 2)
    if total < MENU[order]["cost"]:
        print(f"Sorry ${format(total, '.2f')} is not enough money. Money refunded.")
        return 0
    elif total >= MENU[order]["cost"]:
        if total > MENU[order]["cost"]:
            changes = total - MENU[order]["cost"]
            print(f"Here is ${round(changes, 3)} in change.")
        return MENU[order]["cost"]
    else:
        return 0


def coffee_make(order):
    print(f"Here is your {order} ☕️ Enjoy!")
    resources["water"] -= MENU[order]["ingredients"]["water"]
    if order != "espresso":
        resources["milk"] -= MENU[order]["ingredients"]["milk"]
    resources["coffee"] -= MENU[order]["ingredients"]["coffee"]


def use(save):
    operation = input("What would you like? (espresso/latte/cappuccino): ").lower()
    # 보고서 출력
    if operation == 'report':
        report(save)
    # 커피 주문
    elif operation == 'espresso' or operation == 'latte' or operation == 'cappuccino':
        # 재고 체크
        should_continue_order = check_amount(operation)
        if should_continue_order == 'no':
            return save
        # 투입 금액 체크
        coins = coin_count(operation)
        if coins == MENU[operation]["cost"]:
            save += coins
            # 재고와 투입 금액이 모두 만족되면 커피 제조 후 재고 변경
            coffee_make(operation)
            return save
        else:
            return save
    # 머신 끄기
    elif operation == 'off':
        print("The machine is shut down.")
        return 'off'
    else:
        print("You typed a wrong keyword.")

machine_on = True
while machine_on:
    result = use(profit)
    if result == 'off':
        machine_on = False
    else:
        profit = result
[ 출력 결과 ]

What would you like? (espresso/latte/cappuccino): ❚latte
please insert coins.
How many quarters?: ❚10
How many dimes?: ❚10
How many nickles?: ❚10
How many pennies?: ❚1
Here is $1.51 in change.
Here is your latte ☕️ Enjoy!
What would you like? (espresso/latte/cappuccino): ❚espresso
please insert coins.
How many quarters?: ❚8
How many dimes?: ❚4
How many nickles?: ❚6
How many pennies?: ❚2
Here is $1.22 in change.
Here is your espresso ☕️ Enjoy!
What would you like? (espresso/latte/cappuccino): ❚cappuccino
Sorry there is not enough water.
Sorry there is not enough milk.
What would you like? (espresso/latte/cappuccino): ❚report
Water: 50ml
Milk: 50ml
Coffee: 58g
money: $4.0
What would you like? (espresso/latte/cappuccino): ❚off
The machine is shut down.

🖍️ 답안

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

profit = 0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}


def is_resource_sufficient(order_ingredients):
    """Returns True when order can be made,
    False if ingredients are insufficient."""
    for item in order_ingredients:
        if order_ingredients[item] > resources[item]:
            print(f"Sorry there is not enough {item}.")
            return False
    return True


def process_coins():
    """Returns the total calculated from coins inserted."""
    print("Please insert coins.")
    total = int(input("how many quarters?: ")) * 0.25
    total += int(input("how many dimes?: ")) * 0.1
    total += int(input("how many nickles?: ")) * 0.05
    total += int(input("how many pennies?: ")) * 0.01
    return total


def is_transaction_successful(money_received, drink_cost):
    """Return True when the payment is accepted,
    or False if money is insufficient."""
    if money_received >= drink_cost:
        change = round(money_received - drink_cost, 2)
        print(f"Here is ${change} in change.")
        global profit
        profit += drink_cost
        return True
    else:
        print("Sorry that's not enough money. Money refunded.")
        return False


def make_coffee(drink_name, order_ingredients):
    """Deduct the required ingredients from the resources."""
    for item in order_ingredients:
        resources[item] -= order_ingredients[item]
    print(f"Here is your {drink_name} ☕️. Enjoy!")


is_on = True

while is_on:
    choice = input("What would you like?(espresso/latte/cappuccino):")
    if choice == "off":
        is_on = False
    elif choice == "report":
        print(f"Water: {resources['water']}ml")
        print(f"Milk: {resources['milk']}ml")
        print(f"Coffee: {resources['coffee']}g")
        print(f"Money: ${profit}")
    else:
        drink = MENU[choice]
        if is_resource_sufficient(drink["ingredients"]):
            payment = process_coins()
            if is_transaction_successful(payment, drink["cost"]):
                make_coffee(choice, drink["ingredients"])
  1. 가장 먼저 choice 생성 후 while문 안에 넣기(while문 조건이 정해지지 않았을 때는 우선 True로 지정)
  2. 시크릿 코드 'off'가 입력됐을 경우를 if문으로 지정
    a. while문의 조건을 is_on 으로 변경(머신이 켜져 있는 동안 반복)
  3. 'report'가 입력됐을 경우를 elif문으로 지정
  4. 음료 이름이 입력됐을 경우를 else문으로 지정
    a. 음료 이름이 3개이므로 else문으로 넣는 것이 간단(틀린 글자를 입력한다면 안 되지만)
    b. 선택한 특정 음료를 drink에 저장
  5. is_resource_sufficient 함수 생성
    a. 재고를 조사해서 음료를 제조 가능 여부를 참/거짓으로 반환
    b. for문으로 각 재료 확인(에스프레소의 경우도 따로 if문 만들 필요 없음)
  6. process_coins 함수 생성
    a. 합계를 만드는 코드 대신 동전 종류별로 투입될 때마다 total에 합함
  7. is_transaction_successful 함수 생성
    a. 값이 정상적으로 지불됐는지 여부에 따라 참/거짓 반환
    b. global 키워드로 전역 변수 profit 수정
    c. 돈이 많이 들어왔다면 거스름돈 주기
  8. make_coffee 함수 생성
    a. 실제로 음료를 만들 때 쓴 재료만큼 재고에서 차감
    b. 여기서도 똑같이 for문으로 간단히




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글