I am working through the book and I am stuck on Ex. 21.
For Ex. 21, you define functions for addition, subtraction, multiplication, and division, and you pass arguments a and b to those functions. However, you do not explicitly assign anything to those variables. So, how do the defined functions know what is a and what is b? From the flow of the code, I can deduce what is “a” and what is “b”, but I would like to explicitly know. Does that make sense? How can you pass an argument as a variable to a function without defining that variable first?
To play with the code I added a variable c to the add function:
def add(a,b,c):
print(f”ADDING {a} - {b} - {c}")
return a - b - c
The code runs until I hit:
Traceback (most recent call last):
File "2020-08-18, Ex21.py3", line 31, in <module>
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
TypeError: add() missing 1 required positional argument: 'c'
Why can I not add as many numbers as I want?
The full code is below:
def add(a,b,c):
print(f"ADDING {a} + {b} + {c}")
return a + b + c
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 math with just functions!")
age = add(30, 5, 10)
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 extra credit, type it in anyway
print("Here is the puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")