Home CS61A: Control
Post
Cancel

CS61A: Control

Control

  • Control statements such as if and while control which portions of code are executed, when they are executed, and how many times.

If Statements and Call Expressions

  • Every clause is considered 1) Evaluate the header’s expression
    2) If header is evaluated to be true, execute the suite and skip remaining clauses.
  • The following function would emulate an if statement, but it has a different evaluation rule. 1) Evaluate the operator and then the operand subexpressions
    2) Apply the operator function to the operand arguments.
1
2
3
4
5
def if_(c, t, f):
    if c:
        return t
    else:
        return f
  • The problem with the above code is that whenever if_(c, t, f) is called, all the expressions in the parameters are evaluated before the function is applied onto the parameters, which may result in unexpected behaviorm as the two code statements are ran regardless of what the if statement returns.
    • THIS IS WHY WE NEED CONTROL: They decide which parts of code are ran/not ran.

Control Expressions

  • Allows the skipping of sub expressions.

Shortcircuiting in Logical Operators

  • Shortcircuiting is when the expression returns a value before every expression within it is evaluated.
  • AND (<u> and <v>):
    • Evaluate u. If u is found to be false, then the expression evaluates to be u (or false).
    • If u is True, evaluate to the value of v (either false or true).
  • OR (<u> or <v>):
    • Evaluate u. If u is found to be true, then the expression evaluates to be u (or true).
    • If u is False, evaluate to the value of v (either false or true).
  • Be careful, not every expression in a logical expression is always evaluated.
This post is licensed under CC BY 4.0 by the author.

CS61A: Iteration

CS61A: Higher-Order Functions