
함수의 유형
입 력: 🫙 (빈 유리병)
프로세싱: 🏭 (병입 과정)
출 력: 🥛 (우유로 채운 병)
word_length = len("apple") → word_length = 5# 이름과 성을 입력하면 각 단어의 첫 번째 글자는 대문자, 나머지는 소문자로 변경하는 함수
# 1. 리턴 키워트를 가진 함수 생성
def format_name(f_name , l_name):
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_l_name}" # 리턴
formated_string = format_name("JoN", "skEEt")
print(formated_string)
💡 출력 vs 반환
콘솔로 무언가를 출력하는 것 vs 함수의 출력으로 무언가를 반환하는 것
- 위의 코드에서
f"{formated_f_name} {formated_l_name}"를 그냥 print 하고 함수를 호출해도 되지만,
print 대신 return 키워드를 쓰면 다른 변수에 함수의 출력을 저장하여 사용 가능- 다른 코드 예시
def outer_function(a, b): def inner_function(c, d): return c + d return inner_function(a, b) result = outer_function(5, 10) print(result)15
inner_function의 출력 값은outer_function의 출력 값이 됨
(리턴 키워드를 사용하면 다른 함수에서 해당 함수를 편리하게 호출할 수 있음)
# 이름과 성을 입력하면 각 단어의 첫 번째 글자는 대문자, 나머지는 소문자로 변경하는 함수
# 2. 이름이나 성을 입력하지 않고 지나갔을 경우 조기 종료하기
def format_name(f_name , l_name):
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_l_name}"
print(format_name(input("What's your first name? : "), input("What's your last name? : ")))
Days in Month
연도와 월을 입력하면 해당 월의 일수를 출력하는 프로그램
- 윤년의 2월은 28일까지가 아니라 29일까지 있음
- Leap Year 의 코드 활용
- 윤년인지 아닌지 출력하는 대신
- 윤년일 때는, True 값을 반환
- 윤년이 아닐 때는, False 값을 반환
- month_days 리스트에 모든 월의 표준 일수가 저장되어 있음
- 입력 연도가 윤년일 때는, 입력 월에 맞는 표준 일수 반환
- 입력 연도가 윤년이 아닐 때는, 입력 월을 확인
- 2월이라면, 표준 일수 28이 아닌 29를 출력해야 함
- 2월이 아니라면, 입력 월에 맞는 표준 일수 반환
- 리스트의 인덱스는 0부터 시작하는 것에 주의
def is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
# TODO: Add more code here 👇
def days_in_month(year, month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(year) and month == 2:
return 29
else:
return month_days[month - 1]
#🚨 Do NOT change any of the code below
year = int(input()) # Enter a year
month = int(input()) # Enter a month
days = days_in_month(year, month)
print(days)
숫자, 연산자, 숫자 순으로 입력하면 두 숫자를 연산한 결과가 나오고,
이전 결과값에 이어서 계산을 이어나갈 수 있는 계산기 프로그램
🔍 유의 사항
- 연산 딕셔너리로 사칙연산을 정의한 함수를 호출하기
{"부호": 해당 연산을 정의한 함수 이름}- 키로 값을 호출한 결과를 변수 calculation에 저장하면,
키만 바꿔서 사칙연산 함수(add, subtract, multiply, divide) 모두 사용 가능
⌨️ 작성한 코드
# 사칙연산 정의 함수
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
# 연산 딕셔너리
operations = {"+": add, "-": subtract, "*": multiply, "/": divide}
num1 = int(input("What's the first number? : "))
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation from the line above : ")
num2 = int(input("What's the second number? : "))
calculation = operations[operation_symbol]
answer = calculation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
⌨️ 버그 발생 코드
# 사칙연산
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
# 연산 딕셔너리
operations = {"+": add, "-": subtract, "*": multiply, "/": divide}
# 첫 번째 연산
num1 = int(input("What's the first number? : "))
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation from the line above : ")
num2 = int(input("What's the second number? : "))
calculation = operations[operation_symbol]
first_answer = calculation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {first_answer}")
# 두 번째 연산
operation_symbol = input("Pick another operation : ")
num3 = int(input("What's the next number? : "))
calculation = operations[operation_symbol]
# 버그 발생
second_answer = calculation(calculation(num1, num2), num3)
print(f"{first_answer} {operation_symbol} {num3} = {second_answer}")
calculation(num1, num2)을 그대로 넣을 경우 calculation은 multiply로 바뀌었기 때문에,
(3 * 5) * 3 = 45가 되어버림
🐞디버그
# ...중략...
second_answer = calculation(first_answer, num3)
print(f"{first_answer} {operation_symbol} {num3} = {second_answer}")
calculation(num1, num2)의 리턴값을 first_answer에 저장했기 때문에,
(3 + 5) * 3 = 24가 됨
🔍 유의 사항
- 코드 1은 while문 사용
- 코드 2는 재귀 사용
⌨️ 작성한 코드1 (계산 결과에 계속 이어서 계산하기)
# 사칙연산
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
# 연산 딕셔너리
operations = {"+": add, "-": subtract, "*": multiply, "/": divide}
# 첫 번째 숫자
num1 = int(input("What's the first number? : "))
for symbol in operations:
print(symbol, end=" ")
print("")
should_countinue = True
# while문
while should_countinue:
operation_symbol = input("Pick an operation : ")
num2 = int(input("What's the next number? : "))
calculation = operations[operation_symbol]
answer = calculation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
if input(f"Type 'y' to continue with {answer}, or type 'n' to exit : ") == 'y':
num1 = answer
else:
should_countinue = False
print("Goodbye")
⌨️ 작성한 코드2 (계산 결과를 싹 지우고 새 계산 시작하기)
# 사칙연산
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
# 연산 딕셔너리
operations = {"+": add, "-": subtract, "*": multiply, "/": divide}
# 계산기 함수 정의
def calculator():
num1 = int(input("What's the first number? : "))
for symbol in operations:
print(symbol, end=" ")
print("")
should_countinue = True
while should_countinue:
operation_symbol = input("Pick an operation : ")
num2 = int(input("What's the next number? : "))
calculation = operations[operation_symbol]
answer = calculation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
y_or_n = input(f"Type 'y' to continue with {answer}, 'n' to start a new calculation : ")
if y_or_n == 'y':
num1 = answer
else:
should_countinue = False
# 계산기 함수 재귀 호출 -> 모든 것을 초기화하고 새 계산 시작
calculator()
# 계산기 함수 호출
calculator()
🔍 유의 사항
- 소수점이 있는 숫자를 입력하면 에러 발생하는 부분 수정하기
- 입력한 숫자를 int가 아닌 float으로 형변환하기
- 계산을 초기화하고 처음부터 시작할 때, 콘솔창도 지우도록 clear() 사용
📄 art.py
아스키 로고 아트 저장
⌨️ 작성한 코드
from replit import clear
from art import logo
# 사칙연산
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
# 연산 딕셔너리
operations = {"+": add, "-": subtract, "*": multiply, "/": divide}
# 계산기 함수 정의
def calculator():
print(logo)
num1 = float(input("What's the first number? : "))
for symbol in operations:
print(symbol, end=" ")
print("")
should_countinue = True
while should_countinue:
operation_symbol = input("Pick an operation : ")
num2 = float(input("What's the next number? : "))
calculation = operations[operation_symbol]
answer = calculation(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
y_or_n = input(f"Type 'y' to continue with {answer}, 'n' to start a new calculation : ")
if y_or_n == 'y':
num1 = answer
else:
should_countinue = False
clear()
calculator()
# 계산기 함수 호출
calculator()
[ 출력 결과 ]
_____________________
| _________________ |
| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
| ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | |
| | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | |
| |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | |
| | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | |
| |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | |
| | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | |
| |___|___|___| |___| | | | | || | | || | | || | | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------'
|_____________________|
What's the first number? : 4
+ - * /
Pick an operation : *
What's the next number? : 15
4.0 * 15.0 = 60.0
Type 'y' to continue with 60.0, 'n' to start a new calculation : ...무한 반복 생략...