Skip to content

Latest commit

 

History

History
67 lines (47 loc) · 2.82 KB

File metadata and controls

67 lines (47 loc) · 2.82 KB

Control Structures and Functions

CONTROL STRUCTURES

Conditional Branching

1

In some cases, we can reduce an if ... else statement down to a single conditional expression. The syntax for a conditional expression is:

expression1 if boolean_expression else expression2

Looping

while Loops

2

for Loops

3

EXCEPTION HANDLING

Catching and Raising Exceptions

4

Figure 4.1 Some of Python’s exception hierarchy

5

Figure 4.2 Try ... except ... finally control flows

6

Raising Exceptions

7

Custom Exceptions

class exceptionName (baseException): pass

8

CUSTOM FUNCTIONS

Argument and Parameter Unpacking

9

Accessing Variables in the Global Scope

10 10-1

What stands out here is the use of the global statement. This statement is used to tell Python that a variable exists at the global (file) scope, and that assignments to the variable should be applied to the global variable, rather than cause a local variable of the same name to be created.

11

If we did not use the global statement the program would run, but when Python encountered the Language variable in the if statement it would look for it in the local (function) scope, and not finding it would create a new local variable called Language, leaving the global Language unchanged.

Lambda Functions

lambda parameters: expression

elements.sort(key=lambda e: (e[1], e[2]))
elements.sort(key=lambda e: e[1:3])
elements.sort(key=lambda e: (e[2].lower(), e[1]))

Assertions

assert boolean_expression, optional_expression