Questions
Conceptual
- 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 snipped that said print(x)
. Why?
Solutions
Conceptual Solutions
- Memory Diagram Solution
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.