Nothing to hand in.
Loops that accumulate some new value
n = 6
new_value = 1
for k in range(2, n + 1):
new_value = new_value * k
# Q1: What is the value of new_value here?
# Q2: What would be a better name for new_value?
number_list = [1, -14, 23, 2, 0, 6, 4]
new_value = 0
for number in number_list:
new_value = new_value + number
# Q1: What is the value of new_value here?
# Q2: What would be a better name for new_value?
number_list = [1, -14, 23, 2, 0, 6, 4]
new_value = number_list[0]
for number in number_list:
if number > new_value:
new_value = number
# Q1: What is the value of new_value here?
# Q2: What would be a better name for new_value?
string = 'the moose, the goat, and the emu'
new_string = ''
for ch in string:
if ch != ' ':
new_string = new_string + ch
# Q1: What is the value of new_string here?
# Q2: What would be a better name for new_string?
string = 'the moose, the goat, and the emu'
new_string = ''
for ch in string:
if ord(ch) >= ord('a') and ord(ch) <= ord('z'):
new_string = new_string + ch
# Q1: What is the value of new_string here?
# Q2: What would be a better name for new_string?
# How does one differ from the previous example? Do both work?
string = 'the moose, the goat, and the emu'
new_string = ''
for ch in string:
if ch >= 'a' and ch <= 'z':
new_string = new_string + ch
# Q1: What is the value of new_string here?
# Q2: What would be a better name for new_string?
string = 'The Moose, the Goat, and the Emu'
new_string = ''
for ch in string:
if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z'):
new_string = new_string + ch
# Q1: What is the value of new_string here?
# Q2: What would be a better name for new_string?
Functions
How do you fill in the contents of these functions? How do you test
whether the functions do their jobs properly?
def sum_of_list(number_list):
''' Returns the sum of the elements in number_list. '''
[Your code goes here]
return ???
def max_of_list(number_list):
''' Returns the maximum (i.e. the largest number) of the elements in number_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 ???
Some other functions
def reverse_string(s):
''' Returns the string s, but backwards. '''
[Your code goes here]
return ???
def letter_occurrences(word, letter):
''' Returns the number of times letter occurs in word. '''
[Your code goes here]
return ???