Questions
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.