Conditionals


Questions

True/False

  1. Every if statement must be followed by a paired else branch. (T/F)

  2. Lines contained in an else branch in Python do not have to be indented. (T/F)

  3. You can name a variable else in your program without Python confusing your variable’s name and the else keyword. (If you are unsure, this is a good one to try yourself!) (T/F)

SHOW SOLUTIONS

  1. False

  2. False

  3. False

 

Conceptual

  1. What does the condition of a conditional have to evaluate to in order to enter its then block?

  2. What does the condition of a conditional have to evaluate to in order to enter its else block?

  3. What happens when a return statement is encountered?

SHOW SOLUTIONS

  1. The condition must evaluate to True.

  2. The condition must evaluate to False.

  3. 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()
  1. What is the condition in this code?

  2. What does the condition evaluate to? (Don’t do it in your head, draw a memory diagram!)

  3. What values should x, y, and/or z have to be assigned to in order for the else block to run?

  4. What other values can x, y, and/or z be assigned in order for the if block to run?

SHOW SOLUTIONS

  1. not(x != y and x != "y")

  2. The condition evaluates to True.

  3. To ensure the else block runs in the given code, the condition x != y and x != "y" must be true. This means x should be different from y and x should also be different from the string "y". For example, setting x = "a" and y = "b" will satisfy this condition, making the else block execute.

  4. To make the if block run, the condition not(x != y and x != "y") must be true, which happens when x is either the same as y or the same as "y", or both. In the original code where x = "y", y = "x", and z = "x", the if block runs as not(x != y and x != "y") evaluates to True.

 

Contributor(s): Alyssa Lytle, Viktorya Hunanyan, Megan Zhang, David Karash