@extends('template') @section('title') Lab 3: Conditional Expressions @stop @section('content') Consider the function `category` that takes an integer and returns a single string indicating whether it's even or odd and whether it's negative or not: ```python def category(n): if n%2 == 0: evenOrOdd = 'even' else: evenOrOdd = 'odd' if n < 0: negOrNot = 'neg' else: negOrNot = 'nonneg' return f"{evenOrOdd} {negOrNot}" ``` For example: ``` >>> category{17} 'odd nonneg' >>> category{-42} 'even neg' ``` The body of `category` uses two conditional **statements**, each of which uses the result of a _test expression_ to to choose beween executing a _then branch statement sequence_ or an _else branch statement sequence_. ```python if testExp: thenBranchStm_1 ... thenBranchStm_m else: elseBranchStm_1 ... elseBranchStm_n But Python (and most other programming languages) also has a conditional **expression** construct that uses the result of a _test expression_ to to choose beween the result of evaluating a _then branch expression_ or an _else branch expression_: ```python thenBranchExp if testExp then elseBranchExp ``` It turns out that **expressions** are typically more flexible and powerful than **statements**, so you are strongly encoraged to use conditional **expressions** rather than conditional **statements** in situations where they are sensible. Here is one way to use conditional expressions to implement a version of the `category` function above: ```python ``` @include('/labs/lab03/_toc') @stop