CS 111: Introduction to Computer Science

Lab: loops and functions

Nothing to hand in. This is just for practice.

Goals

Loops

There are several Python types that refer to sequences of some kind. Such types are known as iterable, so you can iterate over them—that is, you can go step-by-step through them in some sense. Among the types we have encountered so far, strings, lists, and open files are iterable:

my_string = 'the moose did not notice the goat' for character in my_string: print(character, ord(character)) my_list = [1, 9, 2, 3, -6, 17] for number in my_list: print(number, 'squared =', number * number) my_open_file = open('moose.txt') print("Let's shout!") for line in my_open_file: print(line.upper()) my_open_file.close()

You can also iterate over sequences of integers, like:

for k in range(10): print(k, 'squared =', k * k) print() print('Do it again, going from 100 to 109') for k in range(100, 110): print(k, 'squared =', k * k) print() print('Check out these odd numbers!') for k in range(1, 20, 2): print(k)

Loops

For each of the tasks described below, write a fragment of Python code to accomplish the task. You can just put all of your fragments in a single Python file, and have them run in sequence.

Functions

For now, our functions will look like this:

def name_of_function(one, or, more, parameters): # Do some computation to compute a result return result

and we will test our functions like this:

answer = name_of_function(4, 3, 2, 1) print('The answer is:', answer)

Try writing and testing the following functions.

def sum_of_list(the_list): ''' Returns the sum of the elements in the_list. ''' [Your code goes here] return ??? def factorial(n): ''' Returns n-factorial. For example, factorial(4) returns 24 (because 1 * 2 * 3 * 4 == 24) ''' [Your code goes here] return ??? def letter_occurrences(word, letter): ''' Returns the number of times letter occurs in word. ''' [Your code goes here] return ???