LPTHW Day 7

13 May 2019

Today’s Progress

# our fuction is called with two arguments(a and b)
def add(a, b):
    print(f"ADDING {a} + {b}") 
   # I add a and b, then return them. When the function ends, any line that runs it will be able to assign this a + b result to a variable, like age.
    return a + b 


def subtract(a, b):
    print(f"SUBTRACTING {a} - {b}")
    return a - b


def multiply(a, b):
    print(f"MULTIPLYING {a} * {b}")
    return a * b


def divide(a, b):
    print(f"DIVIDING {a} / {b}")
    return a / b


print("Let's do some maths with just functions!")

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")

# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print("That becomes: ", what, "Can you do it by hand?")

Thoughts: I hadn’t given it much thought but this exercise reminded me of the differences between “Print” and “Return”. Return !=Print In simple terms, a return statement returns an object that can be passed to another function. A print statement returns a string. More precisely, a print command outputs text directly to the screen, while the return command outputs the values back to whatever is calling the function. Print does what it says. Return does the same thing, returns something from a function to another.

A more text book explanation: When a return statement executes, the expression is evaluated to produce a memory address. That memory address is passed back to the caller, nothing is displayed. When a print statement is executed, the argument(s) are evaluated to produce a memory address and nothing is passed back to the caller. The values at those memory addresses are displayed on the screen.

For the puzzle, this was chaining together returns and passing them into the next function.

divide(iq, 2) = divide(50/2) = 25 
multiply(weight, divide(iq, 2) = multiply(180, 25) = 4500
height = 74
subtract(height, 4500) = 74 - (-4500)= -4426 
age = 35
add(age, 4426) = 35 + (-4426)= -4391
35 + (74 - (180 * (50/2))) = - 4391

Link to work: exercises 20