Quiz 01 Practice
Boolean Expressions
What are the results of the following boolean expressions?
1.1
((not False) and True) == True1.2
(not False) or (True and False)1.3
True and (7 < 3 * 4 / 6)1.4
(not False) != True1.5
not (True and False) and (False or not False)1.6.
"XYz" == "XYZ" or "B" == "C"1.7.
5 ** 2 >= 5 * 5 and 110 % 10 == 0
SHOW SOLUTIONS
1.1. True
1.2. True
1.3. False
1.4. False
1.5. True
1.6. False
1.7. True
Conditionals
True/False
Every
ifstatement must be followed by a pairedelsebranch. (T/F)Lines contained in an
elsebranch in Python do not have to be indented. (T/F)You can name a variable
elsein your program without Python confusing your variable’s name and theelsekeyword. (If you are unsure, this is a good one to try yourself!) (T/F)
SHOW SOLUTIONS
FalseFalseFalse
Conceptual
What does the condition of a conditional have to evaluate to in order to enter its then block?
What does the condition of a conditional have to evaluate to in order to enter its
elseblock?What happens when a return statement is encountered?
SHOW SOLUTIONS
The condition must evaluate to
True.The condition must evaluate to
False.The return value is recorded in memory and the function is immediately exited.
Code Snippet
1 def main() -> None:
2 x: str = "x"
3 y: str = "y"
4 z: str = x
5 y = x
6 x = "y"
7
8 if not(x != y and x != "y"):
9 print(f"x: {x}")
10 else:
11 print("'if' condition not met.")
12
13 main()What is the condition in this code?
What does the condition evaluate to? (Don’t do it in your head, draw a memory diagram!)
What values should
x,y, and/orzhave to be assigned to in order for theelseblock to run?What other values can
x,y, and/orzbe assigned in order for theifblock to run?
SHOW SOLUTIONS
not(x != y and x != "y")The condition evaluates to
True.To ensure the else block runs in the given code, the condition
x != y and x != "y"must be true. This meansxshould be different fromyandxshould also be different from the string"y". For example, settingx = "a" and y = "b"will satisfy this condition, making the else block execute.To make the
ifblock run, the conditionnot(x != y and x != "y")must be true, which happens whenxis either the same asyor the same as"y", or both. In the original code wherex = "y",y = "x", andz = "x", theifblock runs asnot(x != y and x != "y")evaluates toTrue.
Recursion
Conceptual
Which of the following are required in a recursive function that does not infinitely recur?
A base case without a recursive function call
Recursive case that progresses toward the base case
Arguments changing in the recursive case
All of the above
SHOW SOLUTIONS
- All of the above
Memory Diagram
- Create a memory diagram for the following code snippet. Additionally, identify the lines where the edge case, base case, and recursive case occur (this will generally consist of a conditional statement, a return statement, and possibly more lines of code in between).
1 """Recursion practice!"""
2
3 def factorial(num: int) -> int:
4 """Calculate the factorial of num."""
5 if num <= 0:
6 return 1
7 elif num == 1:
8 return 1
9 else:
10 return num * factorial(num=num - 1)
11
12 def main() -> None:
13 """The main function."""
14 print(factorial(num=3))
15
16 main()- Challenge Question: Create a memory diagram for the following code snippet. Identify which lines that base case(s) or recursive case(s) occur on.
"""Recursion practice with palindromes."""
def is_palindrome(word: str, index: int) -> bool:
"""Returns True if word is a palindrome and False otherwise."""
if index >= int(len(word) / 2):
return True
elif word[index] == word[len(word) - (index + 1)]:
return is_palindrome(word=word, index=index + 1)
else:
return False
def main() -> None:
"""The main function."""
print(is_palindrome(word="noon", index=0))
print(is_palindrome(word="110", index=0))
main()SHOW SOLUTIONS
- The edge case occurs on lines 5-6, the base case occurs on lines 7-8, and the recursive case on lines 9-10.

- The base cases occur on lines 5-6 and 9-10. If you reach the base case on lines 5-6 that means you made it through the whole
wordwithout finding any differences between letters that should be the same, so you can returnTrueas the final result. If you make it to lines 9-10, that means a difference was found between letters that should be the same, sowordis not a palindrome. The recursive case is on lines 7-8.

Code Writing
- Write a recursive function named
sumthat has anintparameternumberand returns anintthat is the sum of all nonnegative integers up to and includingnumber(1 + 2 + ... + number). For example,sum(number=4)should evaluate to1 + 2 + 3 + 4 = 10. If a negative argument fornumberis given, just return-1(What case is this?). It may help to come up with your base case and recursive case before beginning to write any code.
SHOW SOLUTIONS
1. The negative argument case is an edge case. Note: There are many equivalent ways this function could be written.
1 def sum(number: int) -> int:
2 """Sum of all nonnegative integers up to and including number."""
3 if number < 0: # Edge case
4 return -1
5 elif number > 0: # Recursive case
6 return number + sum(number=number - 1)
7 else: # Base case
8 return 0
f-strings
What are the printed outputs for the following
printfunction calls?1.1.
print(f"{1 + 1}")1.2.
print(f"C{'OM'}P {100 + 10}")1.3.
print(f"This statement is {not (True or False)}!")1.4.
print(f"Question: Is {55} even? Answer: {55 % 2 == 0}")
SHOW SOLUTIONS
1.1. 2
1.2. COMP 110
1.3. This statement is False!
1.4. Question: Is 55 even? Answer: False
Local Variables
Which of the following properly declares a variable?
"Michael Jordan" = namelarge_number = 2 ** 2025name: str = "Michael Jordan"int: large_number = 2 ** 2025
Which of the following properly updates or assigns a value to a variable (if it has already been declared)?
"Michael Jordan" = namelarge_number = 2 ** 2025name: str = "Michael Jordan"int: large_number = 2 ** 2025
Refer to the following code snippet to answer this question. Describe what will happen if we run this code. Feel free to create a memory diagram to assist you.
1 def foo(num: int) -> None:
2 """Fooey."""
3 x: int = num * -1
4 print(x)
5
6 def main() -> None:
7 """The main function."""
8 foo(4)
9 print(x)
10
11 main()SHOW SOLUTIONS
c:
name: str = "Michael Jordan"The important part to notice is that we are giving it a type, which we only do during declaration.large_number = 2 ** 2025Updating or assigning a value to a variable that has already been declared just uses the equal sign with the variable name on the left and the value on the right, and does not redeclare the type.
When this code is run, you will first enter the
mainfunction since it is called on line 11, then you will enter thefoofunction when it is called on line 8. Then thefoofunction will declare a local variablexand print it, outputting-4. Then we will return to line 8, then move on to line 9 where we attempt to printx. However,xwas a local variable only in thefooframe, not in themainframe, so we will get aNameError.
While Loops
Conceptual
What happens if the condition of a while loop is initially
False?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
whileloop statement starts with,while condition:, what mustconditionevaluate to for the followingwhileloop to execute at least once? What type iscondition?
SHOW SOLUTIONS
- B: The loop will not run at all.
conditionmust beTrueto enter the loop. Its type is abool.
Memory Diagram
Produce a memory diagram for the following code snippet, being sure to include its stack and output.
1 def main() -> None: 2 """Main Function""" 3 y: int = g(1) 4 f(y) 5 print(g(f(3))) 6 7 def f(x: int) -> int: 8 """Function 0""" 9 if x % 2 == 0: 10 print(str(x) + " is even") 11 else: 12 x = x + 1 13 return x 14 15 def g(x: int) -> int: 16 """Function 1""" 17 while x % 2 == 1: 18 x = x + 1 19 return x 20 21 main()1.1. Why is it that
main()is defined abovef()andg(), but we are able to callf()andg()insidemain()without errors?1.2. On line 5, when
print(g(f(3)))is called, is the code block inside of thewhileloop 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.
Code Writing
Write a function named
sum_or_factorialusingwhileloops that has anintparameternumberand behaves in the following way:If
numberis negative, return-1.If
numberis even, return the sum of all positive integers up to and includingnumber.If
numberis odd, return the product of all positive integers up to and includingnumber(the factorial ofnumber).
SHOW SOLUTIONS
Note: There are many ways you could write this function.
1 def sum_or_factorial(number: int) -> int:
2 """Returns the sum up to number if even or the factorial of number if odd."""
3 result: int
4 if number < 0:
5 return -1
6 elif number % 2 == 0:
7 result = 0
8 idx: int = 0
9 while idx <= number:
10 result = result + idx
11 idx = idx + 1
12 else:
13 result = 1
14 idx: int = 1
15 while idx <= number:
16 result = result * idx
17 idx = idx + 1
18 return result