User-Defined Functions

Today we talk about how to write your own functions. So far we have written programs that are essentially long sequences of statements. Your program starts at the top and runs to the bottom. We've called helpful functions along the way, temporarily leaving our sequence to run code in those functions, but then returning to our own sequence to continue on. It's time for you to now define your own functions, so you can write reusable code!

As our programs get longer, they also become harder to read and understand. Functions allow us to separate logical chunks of code out of our sequence. This has two main benefits: (1) reusability, we can run the same code over and over using one function, and (2) readability, your main code is easier to understand because you've simplified it by pulling out complicated executions. This helps you debug errors too.

Read the book chapter. Today's reading is more important than usual.

Reading: Chapter 4 (start at "Adding new functions" and read through the end of the chapter)

You can jump to Chapter 4 here.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

This program prints a right triangle made up of asterisks

def print_repeat(ch, N):
    for i in range(N):
        print(ch, end='')
    print()  # newline
    
# Ask the user for a size.    
times = int(input("How big of a triangle? "))

# Print a right triangle of asterisks.
for i in range(1,times+1):
    print_repeat('*', i)

We've written code to compute the factorial during class. Now that's a great function because it has clear input (the N) and a clear result (the returned N! value).

def factorial(N):
    product = 1
    for i in range(2,N+1):
        product = product * i
    return product

# The main code! Ask the user for an N.
N = int(input("N = "))
fact = factorial(N)
print("Factorial is", fact)