Nothing to hand in. This is just for practice.
Goals
- Practice with loops and functions.
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.
- Print all the positive integers less than 25.
- Print all the positive even numbers less than 25.
- Print a countdown starting at 10 and ending at 0.
- Print all the characters in 'the badger made its plans', one character per line.
- Print the characters in a string of your choice, one character per line, but don't print
the spaces.
- Same, but don't print the spaces, the periods, or the commas.
- Given a list of integers (e.g. my_list = [2, 19, -3, 0, 7]),
print the integers one per line.
- Given a list of integers, print the list in reverse order, one per line.
- Given a list of integers, print the sum of the integers.
- Given a list of integers, print the average (i.e. the mean) of the integers.
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 ???