Questions
Conceptual
- What happens if the condition of a
whileloop is initiallyFalse?
- The loop will run once.
- The loop will not run at all.
- The loop will run infinitely.
- The loop will throw an error.
- If a while loop statement starts with,
while condition:, what mustconditionevaluate to for the followingwhileloop to execute at least once? What type iscondition?
SHOW SOLUTIONS
- The loop will not run at all.
conditionmust beTrueto enter the loop. Its type is a boolean.
Diagram
- 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(str(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 snippet that said print(x). Why?
SHOW SOLUTIONS

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. Therefore, the program does not recognize that x exists in this context.