<jupyter_start><jupyter_text>Conditional Statements in Python    Table of Contents * [Introduction to the `if` Statement](introduction_to_the_`if`_statement)* [Grouping Statements: Indentation and Blocks](grouping_statements:_indentation_and_blocks)    * [Python: It’s All About the Indentation](python:_it’s_all_about_the_indentation)    * [What Do Other Languages Do?](what_do_other_languages_do?)    * [Which Is Better?](which_is_better?)* [The `else` and `elif` Clauses](the_`else`_and_`elif`_clauses)* [One-Line `if` Statements](one-line_`if`_statements)* [Conditional Expressions (Python’s Ternary Operator)](conditional_expressions_(python’s_ternary_operator))* [The Python `pass` Statement](the_python_`pass`_statement)* [ Conclusion](_conclusion)--- From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of **sequential execution** , in which statements are always performed one after the next, in exactly the order specified. But the world is often more complicated than that. Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute. That is where **control structures** come in. A control structure directs the order of execution of the statements in a program (referred to as the program’s control flow). In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:> If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice, then I won’t mow the lawn.) In a Python program, the if statement is how you perform this sort of decision-making. It allows for **conditional** execution of a statement or group of statements based on the value of an expression. The outline of this section is as follows:- First, you’ll get a quick overview of the `if` statement in its simplest form.- Next, using the if statement as a model, you’ll see why control structures require some mechanism for grouping statements together into **compound statements** or **blocks**. You’ll learn how this is done in Python.- Lastly, you’ll tie it all together and learn how to write complex decision-making code.  Introduction to the `if` Statement We’ll start by looking at the most basic type of `if` statement. In its simplest form, it looks like this:```pythonif :    ``` In the form shown above:- `` is an expression evaluated in a Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions section.- `` is a valid Python statement, which must be indented. (You will see why very soon.) If `` is true (evaluates to a value that is “truthy”), then `` is executed. If `` is false, then `` is skipped over and not executed. Note that the colon (`:`) following `` is required. Some programming languages require `` to be enclosed in parentheses, but Python does not. Here are several examples of this type of `if` statement:<jupyter_code>x = 0
y = 5
if x < y:                            # Truthy
    print('yes')
if y < x:                            # Falsy
    print('yes')
if x:                                # Falsy
    print('yes')
if y:                                # Truthy
    print('yes')
if x or y:                           # Truthy
    print('yes')
if x and y:                          # Falsy
    print('yes')
if 'aul' in 'grault':                # Truthy
    print('yes')
if 'quux' in ['foo', 'bar', 'baz']:  # Falsy
    print('yes')
if 10 in [1, 2, 3, 4]:
    print('hi')<jupyter_output><empty_output><jupyter_text>Grouping Statements: Indentation and Blocks So far, so good.But let’s say you want to evaluate a condition and then do more than one thing if it is true:> If the weather is nice, then I will:> > - Mow the lawn> - Weed the garden> - Take the dog for a walk> > (If the weather isn’t nice, then I won’t do any of these things.) In all the examples shown above, each `if `: has been followed by only a single ``. There needs to be some way to say "If `` is true, do all of the following things." The usual approach taken by most programming languages is to define a syntactic device that groups multiple statements into one **compound statement** or **block**. A block is regarded syntactically as a single entity. When it is the target of an `if` statement, and `` is true, then all the statements in the block are executed. If `` is false, then none of them are. Virtually all programming languages provide the capability to define blocks, but they don’t all provide it in the same way. Let’s see how Python does it.  Python: It’s All About the Indentation Python follows a convention known as the [off-side rule](https://en.wikipedia.org/wiki/Off-side_rule), a term coined by British computer scientist <NAME>. (The term is taken from the offside law in association football.) Languages that adhere to the off-side rule define blocks by indentation. Python is one of a relatively small set of [off-side rule languages](https://en.wikipedia.org/wiki/Off-side_ruleOff-side_rule_languages). Recall from the previous section on Python program structure that indentation has special significance in a Python program. Now you know why: indentation is used to define compound statements or blocks. In a Python program, contiguous statements that are indented to the same level are considered to be part of the same block. Thus, a compound `if` statement in Python looks like this:```pythonif :            ...    ``` Here, all the statements at the matching indentation level (lines 2 to 5) are considered part of the same block. The entire block is executed if `` is true, or skipped over if `` is false. Either way, execution proceeds with `` (line 6) afterward. Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is indented less than the lines of the block itself. > **Note:** In the Python documentation, a group of statements defined by indentation is often referred to as a **suite**. This tutorial series uses the terms block and suite interchangeably. Consider the following code:<jupyter_code>if 'foo' in ['bar', 'baz', 'qux']:
    print('Expression was true')
    print('Executing statement in suite')
    print('...')
    print('Done.')
    
print('After conditional')<jupyter_output>After conditional<jupyter_text>The four `print()` statements on lines 2 to 5 are indented to the same level as one another. They constitute the block that would be executed if the condition were true. But it is false, so all the statements in the block are skipped. After the end of the compound `if` statement has been reached (whether the statements in the block on lines 2 to 5 are executed or not), execution proceeds to the first statement having a lesser indentation level: the `print()` statement on line 6. Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent ends the preceding block. The resulting structure is straightforward, consistent, and intuitive. Here is a more complicated `if` block:<jupyter_code># Does line execute?                        Yes    No
#                                           ---    --
if 'foo' in ['foo', 'bar', 'baz']:        #  x
    print('Outer condition is true')      #  x

    if 10 > 20:                           #  x
        print('Inner condition 1')        #        x

    print('Between inner conditions')     #  x

    if 10 < 20:                           #  x
        print('Inner condition 2')        #  x

    print('End of outer condition')       #  x
print('After outer condition')            #  x<jupyter_output>Outer condition is true
Between inner conditions
Inner condition 2
End of outer condition
After outer condition<jupyter_text>What Do Other Languages Do? Perhaps you’re curious what the alternatives are. How are blocks defined in languages that don’t adhere to the off-side rule? The tactic used by most programming languages is to designate special tokens that mark the start and end of a block. For example, in Perl blocks are defined with pairs of curly braces (`{}`) like this:```perl (This is Perl, not Python)if () {    ;    ;    ...    ;};``` C/C++, Java, and a whole host of other languages use curly braces in this way. Other languages, such as Algol and Pascal, use keywords `begin` and `end` to enclose blocks.  Which Is Better? Better is in the eye of the beholder. On the whole, programmers tend to feel rather strongly about how they do things. Debate about the merits of the off-side rule can run pretty hot. On the plus side:- Python’s use of indentation is clean, concise, and consistent.- In programming languages that do not use the off-side rule, indentation of code is completely independent of block definition and code function. It’s possible to write code that is indented in a manner that does not actually match how the code executes, thus creating a mistaken impression when a person just glances at it. This sort of mistake is virtually impossible to make in Python.- Use of indentation to define blocks forces you to maintain code formatting standards you probably should be using anyway. On the negative side:- Many programmers don’t like to be forced to do things a certain way. They tend to have strong opinions about what looks good and what doesn’t, and they don’t like to be shoehorned into a specific choice.- Some editors insert a mix of space and tab characters to the left of indented lines, which makes it difficult for the Python interpreter to determine indentation levels. On the other hand, it is frequently possible to configure editors not to do this. It generally isn’t considered desirable to have a mix of tabs and spaces in source code anyhow, no matter the language. Like it or not, if you’re programming in Python, you’re stuck with the off-side rule. All control structures in Python use it, as you will see in several future tutorials. For what it’s worth, many programmers who have been used to languages with more traditional means of block definition have initially recoiled at Python’s way but have gotten comfortable with it and have even grown to prefer it.  The `else` and `elif` Clauses Now you know how to use an `if` statement to conditionally execute a single statement or a block of several statements. It’s time to find out what else you can do. Sometimes, you want to evaluate a condition and take one path if it is true but specify an alternative path if it is not. This is accomplished with an `else` clause:```pythonif :    else:    ``` If `` is true, the first suite is executed, and the second is skipped. If `` is false, the first suite is skipped and the second is executed. Either way, execution then resumes after the second suite. Both suites are defined by indentation, as described above. In this example, `x` is less than `50`, so the first suite (lines 4 to 5) are executed, and the second suite (lines 7 to 8) are skipped:<jupyter_code>x = 20

if x < 50:
    print('(first suite)')
    print('x is small')
else:
    print('(second suite)')
    print('x is large')<jupyter_output>(first suite)
x is small<jupyter_text>Here, on the other hand, `x` is greater than `50`, so the first suite is passed over, and the second suite executed:<jupyter_code>x = 120

if x < 50:
    print('(first suite)')
    print('x is small')
else:
    print('(second suite)')
    print('x is large')<jupyter_output>(second suite)
x is large<jupyter_text>There is also syntax for branching execution based on several alternatives. For this, use one or more `elif` (short for `else if`) clauses. Python evaluates each `` in turn and executes the suite corresponding to the first that is true. If none of the expressions are true, and an `else` clause is specified, then its suite is executed:```pythonif :    elif :    elif :        ...else:    ``` An arbitrary number of `elif` clauses can be specified. The `else` clause is optional. If it is present, there can be only one, and it must be specified last:<jupyter_code>name = 'Joe'
if name == 'Fred':
    print('Hello Fred')
elif name == 'Xander':
    print('Hello Xander')
elif name == 'Joe':
    print('Hello Joe')
elif name == 'Arnold':
    print('Hello Arnold')
else:
    print("I don't know who you are!")<jupyter_output>Hello Joe<jupyter_text>At most, one of the code blocks specified will be executed. If an `else` clause isn’t included, and all the conditions are false, then none of the blocks will be executed. > **Note:** Using a lengthy `if/elif/else` series can be a little inelegant, especially when the actions are simple statements like `print()`. In many cases, there may be a more Pythonic way to accomplish the same thing.> > Here’s one possible alternative to the example above using f-string:<jupyter_code>name = 'Joe'

if name in ['Fred', 'Xander', 'Joe', 'Arnold']:
    print(f'Hello {name}')
else:
    print("I don't know who you are!")<jupyter_output>Hello Joe<jupyter_text>An `if` statement with `elif` clauses uses short-circuit evaluation, analogous to what you saw with the `and` and `or` operators. Once one of the expressions is found to be true and its block is executed, none of the remaining expressions are tested. This is demonstrated below:<jupyter_code>var  # Not defined
if 'a' in 'bar':
    print('foo')
elif 1/0:
    print("This won't happen")
elif var:
    print("This won't either")<jupyter_output>foo<jupyter_text>The second expression contains a division by zero, and the third references an undefined variable `var`. Either would raise an error, but neither is evaluated because the first condition specified is true.  One-Line `if` Statements It is customary to write if `` on one line and `` indented on the following line like this:```pythonif :    ``` But it is permissible to write an entire if statement on one line. The following is functionally equivalent to the example above:```pythonif : ``` There can even be more than one `` on the same line, separated by semicolons:```pythonif : ; ; ...; ``` But what does this mean? There are two possible interpretations: 1. If `` is true, execute ``.Then, execute ` ... ` unconditionally, irrespective of whether `` is true or not.2. If `` is true, execute all of ` ... `. Otherwise, don’t execute any of them. Python takes the latter interpretation. The semicolon separating the `` has higher precedence than the colon following ``—in computer lingo, the semicolon is said to bind more tightly than the colon. Thus, the `` are treated as a suite, and either all of them are executed, or none of them are:<jupyter_code>if 'f' in 'foo': print('1'); print('2'); print('3')
if 'z' in 'foo': print('1'); print('2'); print('3')<jupyter_output><empty_output><jupyter_text>Multiple statements may be specified on the same line as an `elif` or `else` clause as well:<jupyter_code>x = 2
if x == 1: print('foo'); print('bar'); print('baz')
elif x == 2: print('qux'); print('quux')
else: print('corge'); print('grault')
x = 3
if x == 1: print('foo'); print('bar'); print('baz')
elif x == 2: print('qux'); print('quux')
else: print('corge'); print('grault')<jupyter_output>corge
grault<jupyter_text>While all of this works, and the interpreter allows it, it is generally discouraged on the grounds that it leads to poor readability, particularly for complex `if` statements. [PEP 8](https://www.python.org/dev/peps/pep-0008/other-recommendations) specifically recommends against it. As usual, it is somewhat a matter of taste. Most people would find the following more visually appealing and easier to understand at first glance than the example above:<jupyter_code>x = 3
if x == 1:
    print('foo')
    print('bar')
    print('baz')
elif x == 2:
    print('qux')
    print('quux')
else:
    print('corge')
    print('grault')<jupyter_output>corge
grault<jupyter_text>If an `if` statement is simple enough, though, putting it all on one line may be reasonable. Something like this probably wouldn’t raise anyone’s hackles too much:```pythondebugging = True   Set to True to turn debugging on.    .    .    .if debugging: print('About to call function foo()')foo()```<jupyter_code>if x < 5:
    print('True')
else:
    print('False')<jupyter_output>False<jupyter_text>Conditional Expressions (Python’s Ternary Operator) conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in [PEP 308](https://www.python.org/dev/peps/pep-0308) and green-lighted by Guido in 2005. In its simplest form, the syntax of the conditional expression is as follows:```python if  else ``` This is different from the `if` statement forms listed above because it is not a control structure that directs the flow of program execution. It acts more like an operator that defines an expression. In the above example, `` is evaluated first. If it is true, the expression evaluates to ``. If it is false, the expression evaluates to ``. Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on the ends is returned. Here are some examples that will hopefully help clarify:<jupyter_code>raining = False
print("Let's go to the", 'beach' if not raining else 'library')
raining = True
print("Let's go to the", 'beach' if not raining else 'library')
age = 12
s = 'minor' if age < 21 else 'adult'
s
'yes' if ('qux' in ['foo', 'bar', 'baz']) else 'no'<jupyter_output><empty_output><jupyter_text>> **Note:** Python’s conditional expression is similar to the ` ?  : ` syntax used by many other languages—C, Perl and Java to name a few. In fact, the `?:` operator is commonly called the ternary operator in those languages, which is probably the reason Python’s conditional expression is sometimes referred to as the Python ternary operator.> > You can see in PEP 308 that the ` ?  : ` syntax was considered for Python but ultimately rejected in favor of the syntax shown above. A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers. Of course, there is a built-in function `max()` that does just this (and more) that you could use. But suppose you want to write your own code from scratch. You could use a standard `if` statement with an `else` clause:```pythonif a > b:    m = aelse:    m = b``` But a conditional expression is shorter and arguably more readable as well:```pythonm = a if a > b else b``` Remember that the conditional expression behaves like an expression syntactically. It can be used as part of a longer expression. The conditional expression has lower precedence than virtually all the other operators, so parentheses are needed to group it by itself. In the following example, the `+` operator binds more tightly than the conditional expression, so `1 + x` and `y + 2` are evaluated first, followed by the conditional expression. The parentheses in the second case are unnecessary and do not change the result:<jupyter_code>x = y = 40
z = 1 + x if x > y else y + 2
z
z = (1 + x) if x > y else (y + 2)
z<jupyter_output><empty_output><jupyter_text>If you want the conditional expression to be evaluated first, you need to surround it with grouping parentheses. In the next example, (`x if x > y else y`) is evaluated first. The result is `y`, which is `40`, so `z` is assigned `1 + 40 + 2 = 43`:<jupyter_code>x = y = 40
z = 1 + (x if x > y else y) + 2
z<jupyter_output><empty_output><jupyter_text>If you are using a conditional expression as part of a larger expression, it probably is a good idea to use grouping parentheses for clarification even if they are not needed. Conditional expressions also use [short-circuit evaluation](https://realpython.com/python-operators-expressions/compound-logical-expressions-and-short-circuit-evaluation) like compound logical expressions. Portions of a conditional expression are not evaluated if they don’t need to be.In the expression ` if  else `:- If `` is true, `` is returned and `` is not evaluated.- If `` is false, `` is returned and `` is not evaluated. As before, you can verify this by using terms that would raise an error:<jupyter_code>'foo' if True else 1/0
1/0 if False else 'bar'<jupyter_output><empty_output><jupyter_text>In both cases, the `1/0` terms are not evaluated, so no exception is raised. Conditional expressions can also be chained together, as a sort of alternative `if/elif/else` structure, as shown here:<jupyter_code>s = ('foo' if (x == 1) else
     'bar' if (x == 2) else
     'baz' if (x == 3) else
     'qux' if (x == 4) else
     'quux'
)
s<jupyter_output><empty_output><jupyter_text>It’s not clear that this has any significant advantage over the corresponding `if/elif/else` statement, but it is syntactically correct Python.  The Python `pass` Statement Occasionally, you may find that you want to write what is called a code stub: a placeholder for where you will eventually put a block of code that you haven’t implemented yet.<jupyter_code>name = 'Ali'

if name == 'Ali':
    # TODO: add name to database
    pass
else:
    # TODO: warn user about registeration
    pass

print('here')<jupyter_output>here<jupyter_text>In languages where token delimiters are used to define blocks, like the curly braces in Perl and C, empty delimiters can be used to define a code stub. For example, the following is legitimate Perl or C code:```c This is not Pythonif (x){}``` Here, the empty curly braces define an empty block. Perl or C will evaluate the expression `x`, and then even if it is true, quietly do nothing. Because Python uses indentation instead of delimiters, it is not possible to specify an empty block. If you introduce an `if` statement with `if :`, something has to come after it, either on the same line or indented on the following line. Consider the following code (if you try it you will get `IndentationError`:<jupyter_code>if True:

print('foo')<jupyter_output><empty_output><jupyter_text>The Python `pass` statement solves this problem. It doesn’t change program behavior at all. It is used as a placeholder to keep the interpreter happy in any situation where a statement is syntactically required, but you don’t really want to do anything:<jupyter_code>if True:
    pass

print('foo')<jupyter_output>foo
{'fraction_non_alphanumeric': 0.08148247257158148, 'fraction_numerical': 0.005218089376505218, 'mean_word_length': 4.097294839736303, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 92, 'https://': 5, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '195512', 'license': 'MIT', 'n_tokens_mistral': 6116, 'n_tokens_neox': 5818, 'n_words': 3227, 'path': '01. Python/01. Basics/12 Conditional Statements in Python.ipynb', 'repo_name': 'rostamimahdi1997/CS-Tutorial', 'size': '22431'}