Python 101 · Conditions, Loops, Context Managers

Jan 16, 2016 | Tech Software

Index
Index

Conditional Statements

  • if-elif-else

    : logical branching.

Truthy Falsy Values

if obj:

, while executing it, Python evaluates the following internal logic:
  • bool(): Python first calls for this method; if it exists, its return value (True/False) is used;
  • len(): otherwise, Python calls len(obj); if the result is 0, it returns True; otherwise, it returns False;
  • if neither method is defined, the object is always considered True;
  • note that values such as None, 0, 0j, "" evaluate to False.

Conditional Expressions

Scenario Code Example
Basic Assignment x = a if cond else (b if cond2 else c)
Container Comprehension lst = [a if cond else b for x in list]
Lambda Functions func = lambda x: a if cond else b
Short-Circuit Logic var = name or "Default Value"

Looping

  • for, for-break-else

    : iterates over a sequence.
  • while, do-while

    : repeats a code block while a certain condition remains True.

Loop Control

  • break

    : terminates a loop, inner loop if nested, and executes the line after the loop.
  • continue

    : skips remaining code in a loop, inner loop if nested, and starts the next iteration.
  • pass

    : a syntactical placeholder that does nothing.

Context Manager

  • with

    : automatically handles exceptions, resource allocation and deallocation.