TIL: Python Basics Day 10 - Functions with Outputs, Print vs Return

이다연·2020년 12월 3일
0

Udemy Python Course

목록 보기
10/64

Functions with Outputs

  1. Functions: when you call the function, it helps you to reduce the amount of code you need to write when you want to execute the instruction repeatedly.
  2. Functions with Inputs: inside the parenthesis(), it can be passed over when we call the function. Parameter gets used within the body in the function to modify the code.
  3. Functions with Outputs: allow you to have an output once its completed, with the keyword 'return' it runs and it will go ahead and output the results and replace the line of code. I can save it in another variable which will store the output = result.
    when computer meets the 'return', it knows that it's the end of code and exit the function.
def my_function():
	return 3*2
output = my_function() # -> 6
  • Example code for 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("daYeon", "lEE") #format_name()function is used and assigned to variable
print(formated_string)
 #format_name function is converting letters to Title Case -> Dayeon Lee
  • Example code for Functions with Multiple Returns
    Return was used
    First. below if statement which used as an early exit
    Second. execution part.

Exercise 10.1 Days in Month

  • With a simple logic flow chart, I was able to start writing lines of code.
  • Angela wrote three lines of code for fuction to fully work whereas mine was seven lines for the same execution. She used mutiple 'return'. Simple as that!
def is_leap(year):
  if year % 4 == 0:
    if year % 100 == 0:
      if year % 400 == 0:
        return True #leap year
      else:
        return False
    else:
      return True
  else:
    return False
  
def days_in_month(input_year, input_month):
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  
#-----------------<my code>----------------------------------  
  if is_leap(input_year) == True:
    month_days[1] = 29
    actual_days = month_days[input_month-1]
    return actual_days


  elif is_leap(input_year) == False:
    actual_days = month_days[input_month-1]
    return actual_days

#-----------------<Angela's code>---------------------------
  if is_leap(year) and month == 2:  # if True:
    return 29                       #    return this
  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)
  • Return terminates the function. Anything below return won't be executed.
  • returned output/result from a function: if we wanted to pass it as an input to another function, rather than simply storing it in a variable and print it out.

Docstrings with Function

""" This is a message for you """
When we type the function, the message inside this three quotation marks will get populated in the documentation and appear in a box, documenting fuctions and giving little bit of explaner.
Unlike # comment, Docstrings enable strings with multiple lines, however, python style guide suggests using #s in mutiple lines instead, to avoide any confusion.
#for example
#like this
#multiple lines with #s in each line

Project - Calculator

Flag, Recursion

  • Setting a flag, such as
    should_continue = True
    while should_continue:
  • Recursion: function that calls itself. Be careful that it goes into a infinate loop, if you don't have a condition(flag) that needs to meet in order for this function to call itself.
logo = """
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
"""

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

#Multifly
def multifly(n1, n2):
  return n1 * n2

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

operations = {
  "+": add,
  "-": subtract,
  "*": multifly,
  "/": divide
}

def calculator():
  print(logo)
  num1 = float(input("What's the first number?: "))
  for symbol in operations:
    print(symbol)

  should_continue = True #flag

  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}")

    con_calc = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: \n")
      
    if con_calc == "y":
      num1 = answer #resuable
  
    elif con_calc == "n":
      should_continue = False
      calculator() ###### 1recursion : call its function again
calculator()

I put the each function's name in the dict'operations' as a value,
I let the user pick a symbol and put it in a var: operation_symbol
by making operations[operation_symbol], I can access to value in the dict'operations' which is ,at the same time, a name of function.
var 'calculation_function' has a function's name
var 'answer' holds a return value of each functions.

 calculation_function = operations[operation_symbol]
 	#-> accessing to value with a key in dict 
 answer = calculation_function(num1, num2) 
    #-> return the output of function.
    

num1 holds answer, which is a previously calculated result, only when user wants to continue calculating with current value, var 'num1' will hold answer. otherwhise, freshily starts the calculation.

   if con_calc == "y":
      num1 = answer      #resuable
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글