Quiz 02 Practice


Questions

The quiz itself will be similar in difficulty to this practice worksheet.

Solutions for each problem can be found at the bottom of this page.

Conceptual Questions

  1. Global variables are limited to the scope of the function they are declared in. (T/F)
  2. Variables can have the same name but store different values if they are defined in a different scope. (T/F)
  3. Named constants should be used to store values that may change throughout the program. (T/F)
  4. When using a for...in loop, on the first line of the loop you must specify the type of the variable (variable refers to i in for i in nums). (T/F)

Solutions

While loops and functions

  1. Produce a memory diagram for the following code snippet, being sure to include its stack and output.
    def main() -> None:
        """Main Function"""
        y: int = g(1)
        f(y)
        print(g(f(3)))
        
    def f(x: int) -> int:
        """Function 0"""
        if x % 2 == 0:
            print(f"{x} is even")
        else:
            x += 1
        return x
        
    def g(x: int) -> int:
        """Function 1"""
        while x % 2 == 1:
            x += 1
        return x

    main()

1.1 Why is it that main() is defined above f() and g(), but we are able to call f() and g() inside main() without errors?

1.2 On line 5, when print(g(f(3))) is called, is the code block inside of the while loop ever entered? Why or why not?

1.3 What would happen if a line was added to the end of the snipped that said print(x). Why?

Solution

for Loops

1.1 Rewrite the following code snippet with same functionality using a for ... in loop. 1.2 Rewrite the following code snippet with same functionality using a for ... in range(...) loop.

    stats: list[int] = [7, 8, 9]
    index: int = 0
    total: int = 100
    while index < len(stats):
        total -= stats[index]
        index += 1

Solution

Function Writing

  1. Odd and Even: instructions
  2. Short Words: instructions

Solution

Memory Diagrams

For more practice, make sure to check out the practice memory diagrams.

Solutions

Conceptual Questions Solutions

  1. False
  2. True
  3. False
  4. False

While loops and functions Solution

  1. The memory diagram includes a box on the top labeled Output and a box on the bottom labeled Stack, next to an area labeled Heap.
The first frame in the Stack is labeled Globals and contains the variables main, f, and g. The variable main points to a small box on the heap that says fn 1-5. The variable f points to a small box on the heap that says fn 7-13. The variable g points to a small box on the heap that says fn 15-19.
The next frame on the stack is labeled main and contains a return address and a variable y. The return address is 21 and y has a value of 2. The next frame is labeled g and contains a return address, return value, and a variable x. The return address is 2, the variable x has a value of 2 with the previous value of 1 crossed out, and the return value is 3. The next frame is labeled f and contains a return address, return value, and a variable x. The return address is 4, the variable x has a value of 2, and the return value is 2. The next frame is labeled f and contains a return address, return value, and a variable x. The return address is 5, the variable x has a value of 4 with the previous value of 3 crossed out, and the return value is 4. The final frame is labeled g and contains a return address, return value, and the variable x. The return address is 5, the variable x has a value of 4, and the return value is 4.
The output box contains a line that says (in quotes) 2 is even. Then, on the next line it says (in quotes) 4.

1.1 Even though main is defined before f and g, it isn’t called until after f and g are defined.

1.2 No because x = 4, so x % 2 == 1 is False, and therefore the code block inside is never run.

1.3 There would be an error because x is a local variable inside both f and g. In other words, x is NOT a global variable. Therefore, the program does not recognize that x exists in this context.

for Loop Solutions

1.1

    stats: list[int] = [7, 8, 9]
    total: int = 100
    for elem in stats:
        total -= elem

1.2

    stats: list[int] = [7, 8, 9]
    total: int = 100
    for index in range(0, len(stats)):
        total -= stats[index]

Function Writing Solutions

Note: Your solution does not need to be identical to these, these are just examples of one of many possible solutions.

    def odd_and_even(list1: list[int]) -> list[int]:
        """Find the odd elements with even indexes."""
        i: int = 0
        list2: list[int] = []

        while i < len(list1):
            if list1[i] % 2 == 1 and i % 2 == 0:
                list2.append(list1[i])
            i += 1

        return list2
    def short_words(inp_list: list[str]) -> list[str]:
        """Filter out the shorter words"""
        ret_list: list[str] = []
        for x in inp_list:
            if len(x) < 5:
                ret_list.append(x)
            else:
                print(f"{x} is too long!")
        return ret_list
Contributor(s): Megan Zhang, David Karash, Coralee Vickers, Alyssa Byrnes, Carolyn Pierce