Sunday, January 17, 2021

Python - Function and Output (Day 10)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Built-in function with input and output



Ex:
# Built-in Function: len()
#   input_string": Input
#   string_length: Output
input_string = "Hello World"
string_length = len(input_string)



Custom function with input and output



Ex:
# Custom Function: format_name()
#   'fRANK' and 'CHENG': Input
#   formatted_string   : Output
# title(): https://www.w3schools.com/python/ref_string_title.asp
def format_name(f_name, l_name):
    """Take first name and last name to format it, and
    return the title case version of the name."""

    formatted_f_name = f_name.title()
    formatted_l_name = l_name.title()
    return f"{formatted_f_name} {formatted_l_name}"

formatted_string = format_name("fRANK", "CHENG")
print(formatted_string)



Docstring



Used to provide more information of the function you created. It starts from """ and ends with """.


Challenge - Days in Month



Ex:
# determine the input year is leap year or not
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

# checking how many days in a provided month
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]


year = int(input("Enter a year: "))
month = int(input("Enter a month: "))

days = days_in_month(year, month)
print(days)

Result:
Enter a year: 2022 Enter a month: 2 28



Challenge - Calculator



Ex:
# Add
def add(n_1, n_2):
    return n_1 + n_2

# Sub
def sub(n_1, n_2):
    return n_1 - n_2

# Mul
def mul(n_1, n_2):
    return n_1 * n_2

# Div
def div(n_1, n_2):
    return n_1 / n_2


# Store all operation functions to an dictionary
operations = {
    "+": add,
    "-": sub,
    "*": mul,
    "/": div,
}


def cal():
    # flag
    keep_continue = True

    # Ask for the first number
    num1 = int(input("What's your first number? "))

    # Show operations
    for symbol in operations:
        print(symbol)

    while keep_continue:
        # ask for operator
        operation_symbol = input("Pick an operation: ")

        # Ask for the next number
        num2 = int(input("What's your next number? "))

        answer = operations[operation_symbol](num1, num2)

        print(
            f"{ num1 } {operation_symbol} {num2} =
{operations[operation_symbol](num1, num2)}"
        )

        cal_continue = input(
            f"Type 'y' to continue calculation with { answer }, or
type 'n' to start a new calculation, or type anything
to exit: "
        )

        if cal_continue == "y":
            num1 = answer
        elif cal_continue == "n":
            keep_continue = False
            cal()
        else:
            keep_continue = False


cal()

Result:
What's your first number? 2 + - * / Pick an operation: + What's your next number? 3 2 + 3 = 5 Type 'y' to continue calculation with 5,
or type 'n' to start a new calculation, or type anything to exit: y Pick an operation: * What's your next number? 2 5 * 2 = 10 Type 'y' to continue calculation with 10,
or type 'n' to start a new calculation, or type anything to exit: exit



Why store functions inside a python dictionary?





No comments:

Post a Comment