Conditions and loops ==================== .. admonition:: Precap The default order of execution is sequentially (= from top to bottom, one statement after the other). Sometimes it is required to skip statements under certain conditions or to repeat statements a number of times. This can be done by using the built-in keywords * ``if``, ``elif``, ``else`` for `conditional <#conditional-execution>`__ and * ``for``, ``while``, ``else`` for `repeated <#repeated-execution>`__ execution. Sequential order of execution ----------------------------- By default code will be executed sequentially, i.e. one statement after the other. .. interactive_code_block:: :caption: Statements are executed one after the other (top-down) question = 'Life, The Universe, and Everything' answer = 42 print('The Answer to the Ultimate Question of {} is {}.'.format(question, answer)) Conditional execution --------------------- ``if`` statement ^^^^^^^^^^^^^^^^ Sometimes it is necessary that not all but only selected statements have to be executed based on certain conditions. This type of control can be realized with the built-in keywords ``if``, ``elif``, and ``else``. The basic structure of conditional code is: .. interactive_code_block:: :caption: Pseudo code showing the basic structure of conditional code if : # Statement 1 # Statement 2 # Statement 3 elif : # Statement 4 # Statement 5 elif : # Statement 6 # Statement 7 # Statement 8 # Statement 9 else: # Statement 10 Conditional code always starts with the ``if`` keyword, followed by a condition (= expression that resolves to ``True`` or ``False``) and a colon ``:``. Note the **mandatory** indentation (= preceeded with usually 4 spaces ot 1 tab) of the following *code block* (= one ore more statements). Optionally alternative conditions can be considered using one or more ``elif`` keywords, or, at the end and without any condition an ``else`` keyword. |br| NOTE: The pseudo code above will **throw an error** and syntax coloring also fails. .. interactive_code_block:: :caption: Example: Test if a whole number is even or not whole_number = 123 if whole_number % 2 == 0: result = "even" else: result = "odd" print("{} is an {} number.".format(whole_number, result)) If the condition ``whole_number % 2 == 0`` in line 2 evaluates to ``True``, line 3 will be executed. If it evaluates to ``False`` line 5 will be executed. |br| NOTE: The modulo ``%`` operator in this exampe has the remainder as the result of a division between two numbers. E.g. ``123 % 2`` has ``1`` as a result, because 123 = 61 * 2 + 1. .. Match ^^^^^ Repeated execution ------------------ Sometimes it is necessary that selected statements are executed multiple times. This type of control can be realized with teh built-in keywords ``for``, ``break``, ``continue``, ``while``, and ``else``. There are two options for repeated code: using a sequence with ``for`` or a condition with ``while``. ``for`` loops ^^^^^^^^^^^^^ The basic structure of a ``for`` loop is: .. interactive_code_block:: :caption: Pseudo code showing the basic structure of a for loop for in : # Statement 1 # Statement 2 # Statement 3 if : break # Statement 4 # Statement 5 if : continue else: # Statement 6 # Statement 7 Any sequence data type can be used as sequence (e.g. ``str``, ``tuple``, ``list``). .. interactive_code_block:: :caption: Iterating over a squence of characters in a string horizontal_text_printed = 'Vertically' for character in horizontal_text_printed: print(character) .. interactive_code_block:: :caption: Iterating over a squence of items in a tuple cat_parts = (' ^-^', ' (\\'Y\\')', ' / \\\\ (', '(\\|||/)_)') for cat_part in cat_parts: print(cat_part) A sequence of numbers can be created with the built-in ``range()`` function. .. interactive_code_block:: :caption: Iterating over a squence of numbers using the range() function # Counting from 0 to 4 (!) for i in range(5): print(i) Note that the numbers start at 0 and **stop before** 5. The ``range()`` function can be used in three ways: * Only a stop value: ``range(stop)`` * A start and a stop value: ``range(start, stop)`` * A start, stop and a step value: ``range(start, stop, step)`` .. interactive_code_block:: :caption: Example: A very basic loop using the range() function with start and stop values for i in range(2, 5): print(i) .. interactive_code_block:: :caption: Example: A very basic loop using the range() function with start, stop, and step values for i in range(1, 5, 2): print(i) Depending on the number of function arguments (= the values within the round brackets ``()``) the ``range()`` function can be controlled in different ways. If you have already have a data type that is a sequence, You can directly use that: .. interactive_code_block:: :caption: Example: Iterating (= looping) over a list weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for w in weekdays: print(w) else: print('...the week is over!') Note that the indentation of the code decides which statements are part of the loop and which are not. ``while`` loops ^^^^^^^^^^^^^^^ .. interactive_code_block:: :caption: Pseudo code showing the basic structure of a while loop while : # Statement 1 # Statement 2 # Statement 3 else: # Statement 4 # Statement 5 .. interactive_code_block:: weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] while weekdays: # As long as the list is not empty w = weekdays.pop(0) # Remove the first item from the list print(w) else: print('...the week is over!') References ---------- https://docs.python.org/3/tutorial/controlflow.html