Exercises for Lesson 8

Back to Lesson 8

Exercise 1: Multi-way decisions

For each of the following code snippets, predict what will be printed.

x = 5
y = 10

# (a)
if y % x == 0:
    print("yeppers")
elif y > 3:
    print("so true")
else:
    print("maybe not")

# (b)
if x < y:
    print("cheddar")
elif y != x:
    print("mal")

# (c)
if x < y:
    print("cheddar")
if y != x:
    print("mal")

# (d)
if x == 4:
    print("four")
elif x == 5:
    print("five")
elif y == 8:
    print("eight")
elif y == 10:
    print("ten")
elif y == 12:
    print("twelve")
else:
    print("nada")

Back to Lesson 8

Exercise 2: 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 code

Part 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

Back to Lesson 8

Exercise 3: Count evens

Extend our countEvens function to find the count of even numbers in a list.

def countEvensList(numList):
    """
    Returns the number of even numbers in the given list.
    Assumes the list contains only numbers.
    """
    pass # replace with your code

Back to Lesson 8

Exercise 4: More practice with conditionals

Part a: use a for loop

Further extend your countEvensList function to ask the user for numbers instead of taking in a list.

def countEvensN():
    """
    Asks the user for a series of numbers and returns the count of even numbers.

    Returns: the count of even numbers the user enters
    """
    pass # replace with your code

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 7.1–7.3 (pp. 199–208).

Then, change your countEvensN 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.

Back to Lesson 8