Exercises for Lesson 10
Exercise 1: Conditionals in loops
Part a: Contains 0
Write a function containsZero that returns True if the provided list contains the number 0 and False otherwise.
def containsZero(numList):
"""
Returns True if the list contains 0 as an element and False otherwise.
numList: a list of numbers (each is an int)
returns: a Boolean (True or False)
"""
pass # replace with your codePart b: Find negative
Write a function findNegative that returns the index of the first negative number in the provided list, or -1 if the list contains only non-negative numbers.
def findNegative(numList):
"""
Returns the index of the first negative number in the list, or -1 if not found.
numList: a list of numbers (ints or floats)
returns: the index of the first negative number or -1 (int)
"""
return -1 # replace with your code
Exercise 2: Max of n
Extend our maxOfThree function to compute the maximum number in a list.
def maxOfList(numList):
"""
Returns the maximum number in the given list.
Assumes the list contains only numbers.
"""
pass # replace with your codeExercise 3: More practice with conditionals
Further extend your maxOfList function to ask the user for numbers instead of taking in a list.
def maxOfN():
"""
Asks the user for a series of numbers and returns the largest.
Returns: the largest of the numbers the user enters
"""
pass # replace with your code
Part a: use a for loop
Ask the user for n and then ask for each of the n values in a for loop.
Part b: use a while loop
Read ahead about while loops in Zelle sections 8.1-8.3.2 (pp. 243-252).
Then, change your maxOfN function to instead ask the user to enter numbers one at a time (rather than entering n first) or to enter nothing (just press enter, giving an empty string "") to quit.