[파이썬 중급] 연습문제1

서대철·2023년 7월 14일
0

40_함수 1: 계산기

# 계산기 함수

def add(x, y):
    print(f'{x} + {y} = {x + y}')

def sub(x, y):
    print(f'{x} - {y} = {x - y}')

def mult(x, y):
    print(f'{x} * {y} = {x * y}')

def div(x, y):
    print(f'{x} / {y} = {x / y}')

def rem(x, y):
    print(f'{x} % {y} = {x % y}')

def quot(x, y):
    print(f'{x} // {y} = {x // y}')

def pow(x, y):
    print(f'{x} ** {y} = {x ** y}')

flag = True
while flag:
    print('-' * 308)
    operator = int(input('1. +, \t 2. -, \t 3. *, \t 4. /, \t '
                         '5. %, \t 6. //, \t 7. **, \t  8. exit \t '))
    if operator == 8:
        flag = False
    elif 1 <= operator <= 7:
        x = float(input('enter first number: '))
        y = float(input('enter second number: '))

        if operator == 1:
            add(x, y)
        elif operator == 2:
            sub(x, y)
        elif operator == 3:
            mult(x, y)
        elif operator == 4:
            div(x, y)
        elif operator == 5:
            rem(x, y)
        elif operator == 6:
            quot(x, y)
        elif operator == 7:
            pow(x, y)

    else:
        print('enter a proper number. \n')

41_연습문제 함수2: 거리 계산

# getDistance()
def getDistance(speed, hours, mins):
    return speed * (hours + mins / 60)

speed = float(input('Enter speed (km/h): '))
hours = float(input('Enter hours: '))
mins = float(input('Enter minutes: '))

print('-' * 20)
distance = getDistance(speed, hours, mins)
print(f'{speed} km/h * {hours} hour(s) and {mins} minute(s) = {distance} km')
print('-' * 20)

43_연습문제 함수4: 재귀함수를 이용한 팩토리얼 계산

def formatNum(n):
    return format(n, ',')

def factorial(n):
    if n == 1:
        return n
    return n * factorial(n-1)

inputNum = int(input('enter number: '))

print(formatNum(factorial(inputNum)))

단리/복리 계산기

def formatNum(n):
    return format(n, ',')

def fixed_interest(deposit, duration, annual_rate):
    terminal_interest = 0
    for i in range(duration):
        terminal_interest += deposit * (annual_rate / 100)
    total_terminal = deposit + terminal_interest
    return int(total_terminal)

def compound_interest(deposit, duration, annual_rate):
    duration *= 12    # monthly compound
    monthly_rate = (annual_rate / 12) / 100
    terminal_interest = deposit
    for i in range(duration):
        terminal_interest = terminal_interest + terminal_interest * monthly_rate
    return int(terminal_interest)

deposit = int(input('deposit (won): '))
duration = int(input('duration (year): '))
annual_rate = int(input('annual interest rate(%): '))

# print(formatNum(fixed_interest(deposit, duration, annual_rate)))
# print(formatNum(compound_interest(deposit, duration, annual_rate)))

print('\n')
print('FIXED INTEREST CALCULATOR')
print('=' * 20)
print(f'Deposit: {formatNum(deposit)} won')
print(f'Duration: {formatNum(duration)} year(s)')
print(f'Annual rate: {annual_rate}%')
print('-' * 20)
print(f'Total amount at terminal: \t: {formatNum(fixed_interest(deposit, duration, annual_rate))} won')
print('=' * 20)

print('\n')
print('COMPOUND INTEREST CALCULATOR')
print('=' * 20)
print(f'Deposit: {formatNum(deposit)} won')
print(f'Duration: {formatNum(duration)} year(s)')
print(f'Annual rate: {annual_rate}%')
print('-' * 20)
print(f'Total amount at terminal: \t: {formatNum(compound_interest(deposit, duration, annual_rate))} won')
print('=' * 20)

044_함수 5

등차수열

# my code
def sequence(a1, seq, n):
    line = 1
    line_value = a1
    sum_value = a1
    while line < n+1:
        print(f'line {line} : {line_value}')
        print(f'sum of values up to line {line} : {sum_value}')
        line += 1
        line_value += seq
        sum_value += line_value

a1 = int(input('enter a1: '))
seq = int(input('enter sequence: '))
n = int(input('enter n: '))

sequence(a1, seq, n)
# sample code using For loop
def sequence(a1, seq, n):

    line_value = 0; sum_value = 0
    line = 1

    while line <= n:

        if line == 1:
            line_value = a1
            sum_value += line_value
            print(f'line {line} : {line_value}')
            print(f'sum of values up to line {line} : {sum_value}')

            line += 1
            continue

        line_value += seq
        sum_value += line_value
        print(f'line {line} : {line_value}')
        print(f'sum of values up to line {line} : {sum_value}')

        line += 1

a1 = int(input('enter a1: '))
seq = int(input('enter sequence: '))
n = int(input('enter n: '))

sequence(a1, seq, n)
# sample code using math formula
# sequence formula: an = a1 + (n-1) * d
# sequence sum formula: sn = n*(a1 + an) / 2

def sequence(a1, seq, n):

    line_value = a1
    sum_value = 0
    line = 1

    while line <= 7:
        line_value = a1 + (line - 1) * seq
        sum_value = line * (a1 + line_value) / 2
        print(f'line {line} : {line_value}')
        print(f'sum of values up to line {line} : {sum_value}')

        line += 1

a1 = int(input('enter a1: '))
seq = int(input('enter sequence: '))
n = int(input('enter n: '))

sequence(a1, seq, n)

045_함수 연습문제 6

등비수열

def sequence(a1, ratio, n):
    line_value = 0
    sum_value = 0
    line = 1

    while line <= n:
        if line == 1:
            line_value = a1
            sum_value += line_value
            print(f'line {line} : {line_value}')
            print(f'sum of values up to line {line} : {sum_value}')

            line += 1
            continue

        line_value *= ratio
        sum_value += line_value
        print(f'line {line} : {line_value}')
        print(f'sum of values up to line {line} : {sum_value}')

        line += 1

a1 = int(input('enter a1: '))
ratio = int(input('enter ratio: '))
n = int(input('enter n: '))

sequence(a1, ratio, n)

46_모듈 연습문제1

Pass or Fail

def exampleCode(*scores):

    def getTotal():
        totalScore = sum(scores)
        return totalScore

    def getAverage():
        averageScore = getTotal() / len(scores)
        return averageScore

    def subjectPass():
        for idx, score in enumerate(scores):
            print(f'subject {idx+1}: Pass') if score >= 40 else print(f'subject {idx+1}: Fail')

    def finalPassFail():
        result = 'Final Pass!'

        if getAverage() >= 60:
            for idx, score in enumerate(scores):
                if score < 40:
                    result = 'Final Fail!'
                    break
        else:
            result = 'Final Fail!'

        print(result)

    print(f'Total score: {getTotal()}')
    print(f'Average score: {getAverage()}')
    subjectPass()
    finalPassFail()

실행코드

import passOrFail as pf

s1 = int(input('enter subject 1 score: '))
s2 = int(input('enter subject 2 score: '))
s3 = int(input('enter subject 3 score: '))
s4 = int(input('enter subject 4 score: '))
s5 = int(input('enter subject 5 score: '))

pf.exampleCode(s1, s2, s3, s4, s5)

49_모듈 연습문제4: 순열(permutation)

def getPermutation(n1, n2, logPrint = True):
    result = 1
    for i in range(n1, (n1 - n2), -1):
        if logPrint: print(f'n: {i}')
        result = result * i

    return result

이때, logPrint를 실행파일에서 False로 설정해주면 로그를 출력하지 않을 수 있다.

import permutation2 as pt

num1 = int(input('enter num1: '))
num2 = int(input('enter num2: '))

print(pt.getPermutation(num1, num2, logPrint=False))

0개의 댓글