Why use a function?

Why Functions?

You can reuse code: Define the code once, and use it many times.

Let's look at some lines of code representing the process of making a sandwich:

# make a ham sandwich the old way
print('put a slice of bread')
print('put ham slice')
print('put another slice of bread')
print('A ham sandwich')

# make another ham sandwich
print('put a slice of bread')
print('put ham slice')
print('put another slice of bread')
print('A ham sandwich')

# make another? Ahh?! :-(

Define a function to make a sandwich

def sandwich():
    print('put a slice of bread')
    print('put ham slice')
    print('put another slice of bread')
    print('You got a ham sandwich!')

# Call the function to make a sandwich:
sandwich()

Each time when sandwich() is called, the console will show the result of making a sandwich:

put a slice of bread
put ham slice
put another slice of bread
You got a ham sandwich!

If you like a few more sandwich:

# make another
sandwich()
# make more, ok!
sandwich()
sandwich()
...

If you want 100 sandwich, you can easily call the function in a for loop:

for i in range(100):
    sandwich()

Now you see? Functions provide a high degree of code reusing. Your job as programmer is much easier with functions.

Other than reusing, function makes it possible that you can use the same code many times with different arguments, to produce different results. Let's look at the function parameters in next lesson.

results matching ""

    No results matching ""