1. return
- return은 함수의 결괏값을 돌려주는 명령어입니다.
- 함수는 입력값을 받아 어떤 처리를 한 후에 결과값을 돌려주는 형태입니다.
- 함수에서는 결괏값을 오직 return 명령어로만 돌려받을 수 있습니다.
- 만약 결과값이 없는 경우라면 반환값으로 None을 출력할 것입니다.
ex)
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}"
print(format_name("red", "blue"))
1) 실습예제
exercise)
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
def days_in_month(year, month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
위 코드는 수정하지 않고 중간에 days_in_month(year, month)함수를 수정하여 입력한 달은 몇일까지 있는지 또 윤년인 2월은 29를 출력하는 코드를 작성하세요
Solution)
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
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
return month_days[month - 1]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
2. 계산기
Exercise) 두 수를 입력받아 사칙연산을 수행하는 프로그램을 작성하세요(단, 함수정의 및 호출을 이용해야 합니다.)
Solution)
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
n1 = float(input("First number?\n"))
n2 = float(input("Second number?\n"))
operator = input("which operator do you want? +,-,*,/\n")
if operator == "+":
print(add(n1 ,n2))
elif operator == "-":
print(subtract(n1 ,n2))
elif operator == "*":
print(multiply(n1 ,n2))
elif operator == "/":
print(divide(n1 ,n2))
'Python Study' 카테고리의 다른 글
Python Study(딕셔너리) (0) | 2023.03.06 |
---|---|
Python Study(함수 정의 및 호출 응용) (0) | 2023.03.02 |
Python Study(반복문(While)) (0) | 2023.02.18 |
Python Study(함수 정의 및 호출/들여쓰기) (0) | 2023.02.18 |
Python Study(반복문(for)) (0) | 2023.02.05 |