[udemy] python 부트캠프 _ section 10 _출력과 함수

Dreamer ·2022년 8월 18일
0
post-thumbnail

01. 출력과 함수

def my_function (something):
  # Do this with something
  # Then do this
  # Finally do this
  • Functions with Outputs
def my_function():
  result = 3*2
  return result 
  • output = result = my_function()
#Functions with Outputs

def format_name(f_name, l_name):
  formated_f_name = f_name.title()
  formated_l_name = l_name.title()
  print(f"{formated_f_name},{formated_l_name}")

format_name("angela","yu")
#Functions with Outputs
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("angela","yu")
print(formated_string)

print(format_name("angela","yu"))
len("Angela") 
# string 값의 길이값을 return 형식으로 저장
# 출력하려면 print() 안에 넣어줘야 함. 

02. 다양한 리턴값

#Functions with Outputs
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 is your first name?"),
                 input("What is your last name?")))
  • return 값으로 빈 값을 출력할 수 있다.

03. quiz _ leap year

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 month != 2:
    day = month_days[month-1]
    return day 
  else:
    if is_leap(year) == True:
      return 29
    else:
      return 28
    
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
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)
  • 위에는 내가 작성한 코드, 밑에는 선생님의 코드.확실히 간단하고 압축적이다. 좀 더 코드를 효율적으로 짜는 법을 고민할 필요가 있다.
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):
  if month > 12 or month < 1:
    return "Invalid 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)

04. 독스트링(Docstrings)

  • 독스트링 : 기본적으로 작은 문서를 만드는 방법
  • 함수와 기타 코드 블록을 만들 때 사용 가능하다.
  • 세 개의 따옴표를 사용하여 독스트링을 만들 수 있다.
def format_name(f_name, l_name):
    """ Take a first and last name and format it to return the title case version of the name."""
  • 위와 같은 방법으로 함수를 문서화한다.

05. quiz

def my_function(a):
    if a <40 :
       return
       print("Terrible")
    if a< 80 :
       return "Pass"
    else:
       return "Great"
 print(my_function(25))
  • 다음 코드를 실행한 후 콘솔에 출력되는 값은 : None
  • return 키워드가 함수를 종료해 나머지 코드가 실행되지 않는다.

06. calculator

# Calculator

# Add
def add(n1,n2):
  return n1 + n2

# Substract
def sub(n1, n2):
  return n1-n2

# Multiply
def multi(n1,n2):
  return n1 * n2

# Divide
def divide(n1,n2):
  return n1 / n2 

operations = {
  "+" : add,
  "-" : sub,
  "x" : multi,
  "/" : divide
}

num1 = int(input("What's the first number?: "))
num2 = int(input("What's the second number?: "))

for symbol in operations:
  print(symbol)

operation_symbol = input("Pick an operation from the line above: ")

calculation_function = operations[operation_symbol]
answer = calculation_function(num1,num2)



print(f"{num1} {operation_symbol} {num2} = {answer}") 

07. 출력 vs 반환

  • return / print 차이
  • 함수를 호출해서 얻는 출력값을 반환하지 않고 바로 출력하여 다른 함수의 입력으로 사용하게 되면, 다음과 같은 에러가 생긴다. (값이 틀림)
#Calculator
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)

#Here we select "+"
operation_symbol = input("Pick an operation: ") 
num2 = int(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
first_answer = calculation_function(num1, num2)

print(f"{num1} {operation_symbol} {num2} = {first_answer}")

#Here we select "*" which overides the "+" we selected on line 26.
operation_symbol = input("Pick an operation: ") 
num3 = int(input("What's the next number?: "))

#Here the calculation_function selected will be the multiply() function
calculation_function = operations[operation_symbol] 

#Here the code will be:
#second_answer = multiply(multiply(num1, num2), num3)
second_answer = calculation_function(calculation_function(num1, num2), num3)
#second_answer = 2 * 3 * 3 = 18
#To fix this bug we need to change the code on line 42 to:
second_answer = calculation_function(first_answer, num3)
#In the next lesson, we will delete all the code from line 34-48 so don't worry
#It won't affect your final project.
#But it's a good oportunity to practice debugging. 🐞

print(f"{first_answer} {operation_symbol} {num3} = {second_answer}")
  • calculation_function : 처음에는 + 를 골랐을지라도, 그 후에 *를 선택했기 때문에, second_answer = multiply(multiply(num1, num2), num3) 가 된다.

08. while 반복문, 플래그, 재귀

#Calculator
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)

should_continue = True

while should_continue:
  operation_symbol = input("Pick an operation: ") 
  num2 = int(input("What's the next number?: "))
  calculation_function = operations[operation_symbol]
  answer = calculation_function(num1, num2)

  print(f"{num1} {operation_symbol} {num2} = {answer}")

  if input("Type 'y' to continue calculating with {answer}, or type 'n' to exit. : ") == "y":
    num1 = answer 
  else:
    should_continue = False
    
  • 재귀
#Calculator
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)
  
  should_continue = True
  
  while should_continue:
    operation_symbol = input("Pick an operation: ") 
    num2 = int(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
  
    print(f"{num1} {operation_symbol} {num2} = {answer}")
  
    if input("Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation. : ") == "y":
      num1 = answer 
    else:
      should_continue = False
      calculator()

calculator()
    
  • 재귀 : 함수가 스스로를 호출하는 것, calculator()
  • 단, 이 함수가 스스로를 호출하려면 충족해야 하는 어떤 조건이 있다는 것을 꼭 명시해둬야 한다. 안 그럼 무한으로 스스로를 불러냄.

09. 계산기 마감 작업 및 버그 수정

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)
  should_continue = True
 
  while should_continue:
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear()
      calculator()

calculator()
  • int(input) -> float(input) : 소수점이 있는 숫자도 입력값으로 사용할 수 있다.
profile
To be a changer who can overturn world

0개의 댓글