|
6 | 6 | *******************************************************************************
|
7 | 7 | Control Flow
|
8 | 8 | *******************************************************************************
|
| 9 | + |
| 10 | +``if`` statement |
| 11 | +================ |
| 12 | + |
| 13 | +Perhaps the most well-known statement type is ``if`` statement. For example: |
| 14 | + |
| 15 | +.. code-block:: python |
| 16 | + :caption: if statement base example |
| 17 | + |
| 18 | + >>> x = int(input("Please enter an integer: ")) |
| 19 | + >>> if x < 0: |
| 20 | + ... x = 0 |
| 21 | + ... print("Negative x changed to 0") |
| 22 | + ... elif x == 0: |
| 23 | + ... print("x is equal to zero") |
| 24 | + ... elif x == 1: |
| 25 | + ... print("x is equal to one") |
| 26 | + ... else: |
| 27 | + ... print("x is greater than one") |
| 28 | + |
| 29 | +But let's dive into ``if`` statement with more simple examples. |
| 30 | + |
| 31 | +How it works |
| 32 | +------------ |
| 33 | + |
| 34 | +**if** statement is defined with a keyword ``if`` followed by a Boolean |
| 35 | +expression or any object and finished with colon. The statement requires |
| 36 | +a *body*: other statements to execute, also called an *if block*. |
| 37 | +The body is indented at the same distance from the left (in Python we use |
| 38 | +4 spaces to indent a single block of code). |
| 39 | + |
| 40 | +The body's statements will be executed only in case **if** expression is |
| 41 | +``True``. |
| 42 | + |
| 43 | +.. code-block:: python |
| 44 | + :linenos: |
| 45 | + |
| 46 | + from random import randint |
| 47 | + |
| 48 | + number: int = randint(1, 2) |
| 49 | + |
| 50 | + if not number % 2: # the as number % 2 == 0 |
| 51 | + print(number, "is even") |
| 52 | + |
| 53 | +The ``print`` statement on line #6 will be executed only for even value of |
| 54 | +``number`` variable. |
| 55 | + |
| 56 | +``else`` block |
| 57 | +-------------- |
| 58 | + |
| 59 | +Since ``if`` can be used by its own, it can extend its behavior with ``else`` |
| 60 | +block. The general syntax for ``else`` body is the same: at least one indented |
| 61 | +statement. But ``else`` doesn't take any expression after it. This block of |
| 62 | +code will be executed only that the ``if`` statement truth check fails. |
| 63 | + |
| 64 | +.. code-block:: python |
| 65 | + :linenos: |
| 66 | + |
| 67 | + from random import randint |
| 68 | + |
| 69 | + number: int = randint(1, 2) |
| 70 | + |
| 71 | + if not number % 2: |
| 72 | + print(number, "is even") |
| 73 | + else: |
| 74 | + print(number, "is odd") |
| 75 | + |
| 76 | +``elif`` block(s) |
| 77 | +----------------- |
| 78 | + |
| 79 | +.. todo: provide elif examples |
| 80 | + |
| 81 | +Usage |
| 82 | +----- |
| 83 | + |
| 84 | +.. todo: branching the code |
0 commit comments