Basics of Python
Conditional Execution
Lecture #4
Conditional Execution
Conditional Execution
All the programs in the preceding lectures execute exactly the same statements regardless of the input, if any, provided to them. They follow a linear sequence: Statement 1, Statement 2, etc. until the last statement is executed and the program terminates. Linear programs like these are very limited in the problems they can solve. This lecture introduces constructs that allow program statements to be optionally executed, depending on the context of the program’s execution.
Boolean Expressions
Boolean Expressions
Boolean Expressions
Boolean Expressions
Boolean Expressions
Boolean Expressions
Example:
Boolean Expressions
Output:
Boolean Expressions
The relational operators are binary operators and are all left associative. They all have a lower precedence than any of the arithmetic operators; therefore, Python evaluates the expression:
x + 2 < y / 10
The Simple if Statement
Boolean expressions are essential for a program to be able to adapt its behavior at run time. Most truly useful and practical programs would be impossible without the availability of Boolean expressions.
The Simple if Statement
The general form of the if statement is:
The Simple if Statement
The Simple if Statement
The Simple if Statement
How many spaces should you indent?
The Simple if Statement
A four space indentation for a block is the recommended Python style.
[Whichever indent distance you choose, you must use this same distance consistently throughout a Python program.]
The Simple if Statement
Example:
The if/else Statement
The if statement has an optional else block that is executed only if the Boolean condition is false.
The if/else Statement
Compound Boolean Expressions
Compound Boolean Expressions
Compound Boolean Expressions
Compound Boolean Expressions
Compound Boolean Expressions
Compound Boolean Expressions
Now, consider this example:
The pass Statement
The pass Statement
Nested Conditionals
Nested Conditionals
Multi-way Decision Statements
Multi-way Decision Statements
Multi-way Decision Statements
Multi-way Decision Statements
Multi-way Versus Sequential Conditionals
Multi-way Versus Sequential Conditionals
Conditional Expressions
Conditional Expressions
We can rewrite the above code as:
Conditional Expressions
Example
Q&A