Skip to content

Exercise 7: Functions

Alternative course

Functions

To group sets of code you can use functions. Functions are small parts of repeatable code.
A function accepts parameters. In the example below we have parameter x and y.

Type this program and save it as summation.py

#!/usr/bin/env python3

def dosum(alist):
    sumval = 0
    for l in alist:
        sumval = sumval + l
    return sumval

mylist = [1,2,3,4,5]
print(dosum(mylist))

Save the program below as complexfunction.py

#!/usr/bin/env python3

def doSum(alist):
    sumval = 0
    for l in alist:
        sumval = sumval + l
    return sumval

mylist = [1,2,3,4,5]
print(doSum(mylist))

What you should see

python-function
Function in Python

Study drill

Try the exercises below

1. Make a function that adds two numbers
2. Make a function that prints your name

After completing these continue with the next exercise.

Answers

Exercise 6: While loop
Exercise 7.1: Optional parameters
Published inUncategorized

2 Comments

  1. Anonymous Anonymous

    Shouldn’t they both add up to 15?

    • admin admin

      Thanks! I had updated the code but not the screenshot. All updated now.

Leave a Reply