[Zerobase][Python Mid] 모듈 문제풀이

솔비·2023년 11월 28일
0

💻 Python. w/zerobase

목록 보기
9/33
post-thumbnail

모듈 문제풀이

📖 1번문제

과목별 점수를 입력하면 합격 여부를 출력하는 모듈을 만들어보자

  • 과목별 과락기준 : 40
  • 전체 과락기준 : 과목과락을 하지않고, 평균 60점이상
#모듈
def example_result(*s) :

    pass_score = 60
    limit_score = 40
    txt = []

    def get_total():
        result = sum(s)
        return result

    def get_avg () :
        result = get_total()/len(s)
        return result

    def print_pass_or_fail() :
        for i in s :
            if i <= limit_score :
                txt.append('Fail')
                print('{} : Fail'.format(i))

            else :
                txt.append('Pass')
                print('{} : Pass'.format(i))

    def final_pass_or_fail() :
        print_pass_or_fail()
        if ('Fail' not in txt) :
            if get_avg() >= pass_score :
                print('Final Pass')
        else :
            print('Final Fail')


    print('총점 : {}'.format(get_total()))
    print('평균 : {}'.format(get_avg()))
    final_pass_or_fail()
#실행파일
from module import passorfail as pf


if __name__ == '__main__' :

    score1 = int(input('과목1 점수 입력 : '))
    score2 = int(input('과목2 점수 입력 : '))
    score3 = int(input('과목3 점수 입력 : '))
    score4 = int(input('과목4 점수 입력 : '))
    score5 = int(input('과목5 점수 입력 : '))


    pf.example_result(score1,score2,score3,score4,score5)

📋추가기록

강의의 문제풀이의 경우
모듈 내 함수에 튜플을 사용하지 않고
s1,s2,s3,s4,s5 처럼 모든 점수를 입력해야하는 함수를 만들었으나,
나는 자료구조형태로 코드를 짜보고 싶었다.
총 과락 함수인 final_pass_or_fail()를 코딩할때,
평균은 넘었으나 과목별 점수에 과락이 있으면 어떻게 Fail을 줄 수 있을지 고민하다가
txt리스트를 만들고 print_pass_or_fail()에서 과목별 과락점수를 출력할 때
각 텍스트를 리스트에 넣어 txt리스트에 fail이 있을경우 Final Fail이 출력되게끔 코딩했다.
고민하느라 굉장히 오래걸렸다 ㅎㅎ..😅


📖 2번문제

상품구매개수에 따라 할인율이 결정되는 모듈을 만들자

#모듈

def mart (ps) :

    if len(ps) <= 0:
        print('구매상품이 없습니다.')
        return

    rate = 25
    rates = {1:5,2:10,3:15,4:20}

    if len(ps) in rates :
        rate = rates[len(ps)]

    total_price = int(sum(ps) * (1- (rate*0.01)))

    print('할인율 : {}'.format(rate))
    print('합계 : {}'.format(total_price))
#실행파일

from module import mart as m

prices = []

while True :

    buy = int(input('상품을 구매하시겠어요? 1.구매 2.종료 : '))
    if buy == 1 :
        pay = int(input('상품 가격 입력 : '))
        prices.append(pay)

    elif buy == 2:
        m.mart(prices)
        break

📋추가기록

return이 없으면 None이 출력된다고 했는데,
매번 달라서 너무 헷갈린다.
print를 해야할지 return을 해야할지도..

🌟 return을 사용할때

early return의 경우 많이 사용한다. 맥락 상 break와 유사한 효과를 내기 때문에, 무언가를 리턴하기 보다는 실행 중단의 의미가 더 크다.

🌟 return을 사용하지 않을 때

함수가 무언가를 반환하는게 목적이 아닌, 단순 연산의 목적일 경우이다.
연산이 끝난 후 연산 성공이나 실패를 반환해야 한다면 달라지겠지만, 그게 아니라 단순히 글로벌 변수 연산이 목적이라면, 사용하지 않는 경우가 있다.

찾아본 자료에서는 이렇게 나와있었는데,
무슨소리인지 아직 잘 이해가 가지는 않고,

내가 정리해본 내용은

모듈내에 return값 없음
-> print(함수)
= None 출력
-> 함수만호출
= None 미출력

위 연습문제의 경우
모듈 내에서 ps의 길이가 0이하면 return
여기서 return은 실행중단의 의미
1초과면 rate와 total_price print

실행파일에서 mart함수를
단순호출 시 -> None 출력되지않음
print 시 -> None 출력됨을 알 수 있었다.
(긁적)


📖 3번문제

로또모듈을 만들고 로또 결과가 출력 될 수 있도록 프로그램을 만들어보자

#모듈

import random

user_nums = []
rand_nums = []
collect_nums = []
bonus = 0

def set_user_nums(ns):								#선택번호를 담는 함수
    global user_nums
    user_nums = ns

def get_user_nums():
    return user_nums

def set_rand_nums():								#로또번호를 담는 함수
    global rand_nums
    rand_nums = random.sample(range(1,46),6)

def get_rand_nums():
    return rand_nums

def set_bonus_num ():								#보너스번호를 담는 함수
    global bonus

    while True :			#보너스 번호와 로또번호가 일치하지 않게 while문
        bonus = random.randint(1,46)
        if bonus not in rand_nums :
            break

def get_bonus_num () :
    return bonus


def lotto_result ():								#로또결과함수
    global collect_nums
    global rand_nums
    global user_nums
    global bonus

    for i in user_nums :
        if i in rand_nums :
            collect_nums.append(i)

    if len(collect_nums) == 6:
        print('1등당첨')
        print('일치번호 : {}'.format(collect_nums))

    elif (len(collect_nums) == 5) and (bonus in user_nums) :
        print('2등당첨')
        print('일치번호 : {}, 보너스번호 : {}'.format(collect_nums,bonus))

    elif len(collect_nums) == 5:
        print('3등당첨')
        print('일치번호 : {}'.format(collect_nums))


    elif len(collect_nums) == 4:
        print('4등당첨')
        print('일치번호 : {}'.format(collect_nums))

    elif len(collect_nums) == 3:
        print('5등당첨')
        print('일치번호 : {}'.format(collect_nums))

    else :
        print('다음기회에')
        print('일치번호 : {}'.format(collect_nums))

        print('로또번호 : {}'.format(rand_nums))
        print('보너스번호 : {}'.format(bonus))
        print('선택번호 : {}'.format(user_nums))


def start_lotto():									#로또실행함수
    n1 = int(input('번호1~45 입력 : '))
    n2 = int(input('번호1~45 입력 : '))
    n3 = int(input('번호1~45 입력 : '))
    n4 = int(input('번호1~45 입력 : '))
    n5 = int(input('번호1~45 입력 : '))
    n6 = int(input('번호1~45 입력 : '))
    select_nums = [n1,n2,n3,n4,n5,n6]

    set_user_nums(select_nums)
    set_rand_nums()
    set_bonus_num()
    lotto_result()
#실행파일
from module import lotto as l

l.start_lotto()

📋추가기록

게터와 세터 함수를 만드는 이유는 클래스에서 다시 복습하기로했다.
(강의에서 설명이 없어서 유튜브를 봤는데, 소화가 되지 않는다)
모듈파트에서 제일 헷갈리는건은
어디까지 모듈에 담고 어디부터 실행파일에 코딩해야하는지 이다.
사용자가 직접 사용했을 때를 기준을 생각해보려고 하는데,
아직 쉽지 않다.


📖 4번문제

수입과 공과금을 입력하면 공과금 총액과 수입대비 공과금 비율을 계산하는 모듈

#모듈

income = 0
water_bill = 0
electric_bill = 0
gas_bill = 0

def set_income (m) :
    global income
    income = m

def get_income():
    return income

def set_water(w) :
    global water_bill
    water_bill = w

def get_water():
    return water_bill

def set_electric (e) :
    global electric_bill
    electric_bill = e

def get_electric () :
    return electric_bill

def set_gas (g) :
    global gas_bill
    gas_bill = g

def get_gas () :
    return gas_bill

def bill_sum ():
    global electric_bill
    global water_bill
    global gas_bill

    result = electric_bill+water_bill+gas_bill
    print('공과금 : {}'.format(format(result,',')))
    return result

def rate() :
    global income

    result2 = bill_sum() / get_income() *100
    print('공과금 비율 : {}%'.format(result2))
    return result2

def start():
    i = int(input('수입 : '))
    eb = int(input('전기요금 : '))
    wb = int(input('수도요금 : '))
    gb = int(input('가스요금 : '))

    set_income(i)
    set_electric(eb)
    set_gas(gb)
    set_water(wb)
    rate()

#실행파일

from module import rate as r

r.start()

제로베이스 데이터취업스쿨
Daily Study Note
profile
Study Log

0개의 댓글