Lesson Notes
To use a vending machine we must give it 2 things:
If you enter a specific code and the money required for the item, you get the item.
You probably don’t know how the internal mechanics for the transaction works, but you don't need to. The coin slot and buttons are the interface to the vending machine black box
Black Boxing: hiding away complexity with an abstract, simple interface
Often we write the same code again and again with only slight changes. The algorithm is the same, only the data changes
A vending machine has a pre-written algorithm that will run when given input. We can also pre-write algorithms in Python if we know our program is going to need them.
Just like variables do for data, functions give us a way to store an an algorithm in memory and use it by name.
You have already been using functions in your programs:
print("Hello") # algorithm to write to the console
The algorithm to print to the console is always the same, the only thing that changes is the data printed
input("enter some text:") # algorithm to print a message, then read from the console
The algorithm for input always takes in whatever the user types as a string and leaves it up to the programmer to change it to the correct type. The only thing that changes is the length of the input string.
def my_func(): #notice the colon. It’s required!
print("statement") #notice the indentation. It’s required!
print("other statement")
my_func()
print("done")
my_func()
Code indented under the function name is called the function block.
def <function_name>(): #interface
<statements...>
The function ‘ends’ when you un-indent the block
def name( ):
statement_1 # part of the function's algorithm
statement_2 # part of the function's algorithm
not_part_of_the_function = “some text”
What can go in a function?
Any valid python code can go inside the function
Let’s say we wanted to write a program that asks the user for 3 numbers, and prints the lowest of the 3.
However, we want to do this 3 times throughout our program (not consecutively).
We don’t want to write the same code 3 times. We should use functions!
The function must:
def find_min():
print("Please enter 3 numbers")
num_a = int(input(":")) # 10
num_b = int(input(":")) # 5
num_c = int(input(":")) # 2
lowest = num_a
if num_b < lowest:
lowest = num_b
if num_c < lowest:
lowest = num_c
print(lowest)
find_min()
#do other stuff
find_min()
#do other stuff
find_min()