这是用户在 2024-3-19 1:03 为 http://localhost:8888/notebooks/Desktop/%E7%BC%96%E7%A8%8B%E8%80%83%E8%AF%953.25/%E7%BC%96%E7%A8%8B%... 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
0

04_control_flow.ipynb

    1. Lecture 4: Control Flow
      1. Outline
      2. What is the Flow of Execution?
      3. Control Flow Generic Form
      4. Control Flow I: Repetition
      5. `while`-loop: Simple Countdown
      6. `while`-loop: Deconstructing the Header
      7. `while`-loop: Newton’s method
      8. `while`-loop: Nested
      9. Endless loops (Type of Errors III)
      10. `for`-loop: Simple Countdown
      11. `for`-loop: Deconstructing the Header
      12. `for`-loop: Iterable Sequences – Range
      13. `for`-loop: Iterable Sequences – String
      14. `for`-loop: Iterable Sequences – Vector
      15. `for`-loop: Nested
      16. Control Flow II: Conditional Execution
      17. Deconstructing the `if`-statement Header
      18. Alternative Conditional Execution
      19. Chained Conditional Execution
      20. Nested Conditional Execution
      21. Propositional Logic Truths Tables
      22. Logical Operators
      23. Summary: Looking Back and Looking Forward
Skip to Main 跳到主要
Jupyter

04_control_flow 04_控制流

Last Checkpoint: 4 months ago
最后检查点:4 个月前
  • File 文件
  • Edit 编辑
  • View 看法
  • Run
  • Kernel 核心
  • Settings 设置
  • Help 帮助
JupyterLab Jupyter实验室
Julia 1.9.3 朱莉娅1.9.3
Kernel status: Idle 内核状态:空闲
    <img src="https://www.dpo.rwth-aachen.de/global/show_picture_asis.asp?id=aaaaaaaabftpwfx" width=200 height=200 align="left" /> <img src="https://www.dpo.rwth-aachen.de/global/show_picture_asis.asp?id=aaaaaaaabftpxde" width=200 height=200 align="right" />

    Image Image

    <h1><center> Introduction to Programming for Business Analytics </center></h1>

    <p style="text-align:left;">
    Murwan Siddig, Stefan Pilot
    </p>
    <a href="mailto:ipba@dpo.rwth-aachen.de">ipba@dpo.rwth-aachen.de</a> <br>

    Introduction to Programming for Business Analytics
    业务分析编程简介
    ¶

    Murwan Siddig, Stefan Pilot
    穆尔万·西迪格、斯特凡·派洛特

    ipba@dpo.rwth-aachen.de
    ## Lecture 4: Control Flow

    Lecture 4: Control Flow¶
    第 4 讲:控制流 ¶

    ----
    ### Outline
    - The flow of Execution
    - Control Flow I: Repetition
    - The `while`-loop
    - Endless loops (Types of errors II)
    - The `for`-loop
    - Control Flow II: Conditional Execution

    Outline¶ 大纲 ¶

    • The flow of Execution
      执行流程
    • Control Flow I: Repetition
      控制流程 I:重复
      • The while-loop  while 循环
      • Endless loops (Types of errors II)
        无限循环(错误类型 II)
      • The for-loop  for 循环
    • Control Flow II: Conditional Execution
      控制流二:条件执行
    ---
    ### What is the Flow of Execution?

    The flow of execution is the order in which statements are executed.
    - Execution begins at the first statement of the program (i.e., the first line of code) and statements are run one at a time:
    - ($\rightarrow$) from left to right.
    - ($\downarrow$) from top to bottom.
    - **Repetition** and **conditional execution** allow us to *control* the *flow of execution*.
    - **Repetition:** Control **how often** certain parts of the code are executed.
    - **Conditional execution:** Control **whether** certain parts of the program are executed.


    What is the Flow of Execution?¶
    执行流程是怎样的? ¶

    The flow of execution is the order in which statements are executed.
    执行流程是语句的执行顺序。

    • Execution begins at the first statement of the program (i.e., the first line of code) and statements are run one at a time:
      执行从程序的第一条语句(即第一行代码)开始,并且一次运行一个语句:

      • (→) from left to right.
        ( → ) 从左到右。
      • (↓) from top to bottom.
        ( ↓ ) 从上到下。
    • Repetition and conditional execution allow us to control the flow of execution.
      重复和条件执行使我们能够控制执行流程。

      • Repetition: Control how often certain parts of the code are executed.
        重复:控制代码某些部分的执行频率。
      • Conditional execution: Control whether certain parts of the program are executed.
        条件执行:控制程序的某些部分是否被执行。
    ---
    ### Control Flow Generic Form

    Control Flow statements have the following generic form:

    ```
    HEADER
    BODY
    END
    ```

    - **Header:** Declares the start, and the specifics, of the statement.
    - Contains a keyword that indicates the type of the statement.
    - The keyword is followed by another expression depending on the type of the statement.
    - **Body:** Contains the (expressions) part of the program being controlled.
    - For readability every expression in the body is indented.
    - There is no limitation on the number of expressions in the body.
    - **Termination expression:** Indicates where the control flow statement ends.
    - The termination expression is done using the keyword `end`.

    Control Flow Generic Form¶
    控制流通用形式 ¶

    Control Flow statements have the following generic form:
    控制流语句具有以下通用形式:

    HEADER
        BODY
    END
    
    • Header: Declares the start, and the specifics, of the statement.
      标题:声明语句的开始和细节。

      • Contains a keyword that indicates the type of the statement.
        包含指示语句类型的关键字。
      • The keyword is followed by another expression depending on the type of the statement.
        根据语句的类型,关键字后跟另一个表达式。
    • Body: Contains the (expressions) part of the program being controlled.
      主体:包含被控制程序的(表达式)部分。

      • For readability every expression in the body is indented.
        为了便于阅读,正文中的每个表达式都缩进。
      • There is no limitation on the number of expressions in the body.
        正文中的表达式数量没有限制。
    • Termination expression: Indicates where the control flow statement ends.
      终止表达式:表示控制流语句的结束位置。

      • The termination expression is done using the keyword end.
        终止表达式使用关键字 end 完成。

    Note: Indentation is a blank space, before the start of a sentence, produced by a single TAB (⇥).
    注意:缩进是句子开头之前的空格,由单个制表符 (⇥) 产生。

    ----
    ### Control Flow I: Repetition
    *Repetition* is when we evaluate certain expressions (usually with some variation), repeatedly, until a specified termination criterion is reached.
    - Repetition is done using a **loop-statement**.
    - A *loop-statement* is an instruction that repeats until the termination criterion is reached.
    - Each round of repetition in a loop-statement is called an *iteration*.

    Control Flow I: Repetition¶
    控制流程 I:重复 ¶

    Repetition is when we evaluate certain expressions (usually with some variation), repeatedly, until a specified termination criterion is reached.
    重复是指我们反复评估某些表达式(通常带有一些变化),直到达到指定的终止标准。

    • Repetition is done using a loop-statement.
      重复是使用循环语句完成的。
      • A loop-statement is an instruction that repeats until the termination criterion is reached.
        循环语句是重复执行直到达到终止标准的指令。
      • Each round of repetition in a loop-statement is called an iteration.
        循环语句中的每一轮重复称为迭代。
    ![generic_loop.jpg](attachment:generic_loop.jpg)

    generic_loop.jpg

    - There are two types of loops:
    - **`while`-loop:** termination condition is based on a *Boolean expression* (`Bool` value).
    - **`for`-loop:** termination condition is based on a *range* or a *sequence* of values.
    - In this lecture, we will focus on while-loops

    - **Question:** Why do we need to execute the same code repeatedly?
    - **Answer:** Repetition is very useful in automating repetitive tasks without making errors.
    • There are two types of loops:
      有两种类型的循环:

      • while-loop: termination condition is based on a Boolean expression (Bool value).
        while -loop:终止条件基于布尔表达式( Bool 值)。
      • for-loop: termination condition is based on a range or a sequence of values.
        for -loop:终止条件基于值的范围或序列。
    • In this lecture, we will focus on while-loops
      在本次讲座中,我们将重点关注 while 循环

    • Question: Why do we need to execute the same code repeatedly?
      问题:为什么我们需要重复执行相同的代码?

    • Answer: Repetition is very useful in automating repetitive tasks without making errors.
      回答:重复对于自动执行重复性任务而不出错非常有用。

    ----
    ### `while`-loop: Simple Countdown

    Suppose you want to write a program that prints (in each new line) a countdown from `10` to `1`.

    - Chances are, you thought of writing something like this:

    while-loop: Simple Countdown¶
    while -loop:简单倒计时 ¶

    Suppose you want to write a program that prints (in each new line) a countdown from 10 to 1.
    假设您要编写一个程序来打印(在每个新行中)从 10 到 1 的倒计时。

    • Chances are, you thought of writing something like this:
      您很可能想写这样的东西:
    [ ]:
    println(10)
    println(9)
    println(8)
    println(7)
    println(6)
    println(5)
    println(4)
    println(3)
    println(2)
    println(1)
    What if the countdown starts from `100`? What about `1000000000000`?

    $\implies$ Using a `while`-loop, we can perform a countdown, from any number, in a concise manner.

    What if the countdown starts from 100? What about 1000000000000?
    如果倒计时从 100 开始怎么办? 1000000000000 怎么样?

    ⟹ Using a while-loop, we can perform a countdown, from any number, in a concise manner.
    ⟹ 使用 while 循环,我们可以以简洁的方式从任意数字执行倒计时。

    [ ]:
    countdown = 10
    while countdown > 0
    println(countdown)
    countdown -= 1
    end
    [ ]:
    countdown = 100
    while countdown > 0
    println(countdown)
    countdown -= 1
    end
    ----
    ### `while`-loop: Deconstructing the Header

    A `while`-loop statement has the following generic form.<br>

    ```julia
    while BOOLEAN_EXPRESSION
    BODY
    end
    ```

    - The header consists of the keyword `while` followed by a Boolean expression (`BOOLEAN_EXPRESSION`).
    - The Boolean expression defines the stopping condition.
    - Recall that a Boolean expression evaluates to a `Bool` value: either `true` or `false`.
    - As long as (*while*) `BOOLEAN_EXPRESSION` evaluates to `true`, the loop will continue.
    - As soon as the `BOOLEAN_EXPRESSION` evaluates to `false`, the loop will be stopped.

    The `while`-loop can almost be read as English: "*While* the condition is *true* evaluate the body of the code. When the condition becomes *false* stop."

    while-loop: Deconstructing the Header¶
    while -loop:解构标头 ¶

    A while-loop statement has the following generic form.
    while 循环语句具有以下通用形式。

    while BOOLEAN_EXPRESSION
        BODY
    end
    • The header consists of the keyword while followed by a Boolean expression (BOOLEAN_EXPRESSION).
      标头由关键字 while 后跟布尔表达式 ( BOOLEAN_EXPRESSION ) 组成。
    • The Boolean expression defines the stopping condition.
      布尔表达式定义停止条件。
      • Recall that a Boolean expression evaluates to a Bool value: either true or false.
        回想一下,布尔表达式的计算结果为 Bool 值: true 或 false 。
        • As long as (while) BOOLEAN_EXPRESSION evaluates to true, the loop will continue.
          只要 (while) BOOLEAN_EXPRESSION 的计算结果为 true ,循环就会继续。
        • As soon as the BOOLEAN_EXPRESSION evaluates to false, the loop will be stopped.
          一旦 BOOLEAN_EXPRESSION 计算结果为 false ,循环就会停止。

    The while-loop can almost be read as English: "While the condition is true evaluate the body of the code. When the condition becomes false stop."
    while 循环几乎可以读作英语:“当条件为 true 时评估代码主体。当条件变为 false 时停止。”

    ----
    ### `while`-loop: Newton’s method

    - Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.
    - For example, one way of computing the square root of a number $a$ is Newton’s method where you start with (almost) any estimate $x_0$ and improve this estimate with the following formula:

    $$
    x_{k+1} = \frac{1}{2}(x_{k} + \frac{a}{x_{k}})
    $$

    - $x_k$ indicates the value of the estimate after $k$ iterations, and it is updated repeatedly using this formula until it converges to $\sqrt{a}$.

    Suppose you want to write a program that starts with an initial estimate $x_0$ and improves it until it can no longer be improved.

    while-loop: Newton’s method¶
    while -loop:牛顿法 ¶

    • Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.
      循环通常用在通过从近似答案开始并迭代改进它来计算数值结果的程序中。
    • For example, one way of computing the square root of a number a is Newton’s method where you start with (almost) any estimate x0 and improve this estimate with the following formula:
      例如,计算数字 a 的平方根的一种方法是牛顿法,您可以从(几乎)任何估计 x0 开始,并使用以下公式改进该估计:

    xk+1=12(xk+axk)

    • xk indicates the value of the estimate after k iterations, and it is updated repeatedly using this formula until it converges to a.
      xk 表示经过 k 次迭代后的估计值,并使用该公式重复更新,直到收敛到 a 。

    Suppose you want to write a program that starts with an initial estimate x0 and improves it until it can no longer be improved.
    假设您要编写一个程序,从初始估计 x0 开始,然后对其进行改进,直到无法再改进为止。

    [ ]:
    # find the square root of a
    a = 81;
    x = 0.0001;
    y = (x + a/x) / 2
    while y != x
    x = y
    println("x = ", x)
    y = (x + a/x) / 2
    end
    ----
    ### `while`-loop: Nested
    We can nest multiple `while`-loops within one another.

    while-loop: Nested¶
    while -循环:嵌套 ¶

    We can nest multiple while-loops within one another.
    我们可以将多个 while 循环嵌套在一起。

    [ ]:
    suits = ["♠", "♦", "♥", "♣"] #[\spadesuit \:diamonds:, \:hearts:, \clubsuit]
    suit_count = 0;
    while suit_count < length(suits)
    suit_count += 1
    ranks_count = 0;
    while ranks_count < 13
    ranks_count += 1
    println("$(suits[suit_count]) $(ranks_count)")
    end
    end
    ---
    ### Endless loops (Type of Errors III)

    Endless loop, also known as an infinite loop, is a loop that continues to run indefinitely.

    Endless loops (Type of Errors III)¶
    无限循环(错误类型 III) ¶

    Endless loop, also known as an infinite loop, is a loop that continues to run indefinitely.
    无限循环,也称为无限循环,是无限期地持续运行的循环。

    [ ]:
    while true
    println("This is an endless loop. Press Ctrl+C to exit.")
    end
    ----
    ### `for`-loop: Simple Countdown

    An alternative way to perform repetition is to use a `for`-loop statement.

    for-loop: Simple Countdown¶
    for -loop:简单倒计时 ¶

    An alternative way to perform repetition is to use a for-loop statement.
    执行重复的另一种方法是使用 for 循环语句。

    [ ]:
    countdown = 10
    for i in 1:10
    println(countdown)
    countdown -= 1
    end
    ---
    ### `for`-loop: Deconstructing the Header

    The `for`-loop statement has the following generic form.

    ```julia
    for ITERATOR in ITERABLE_SEQUENCE
    BODY
    end
    ```

    - The header starts with the keyword `for`.
    - The keyword `for` is followed by an iterator variable (`ITERATOR`), the keyword `in`, and an iterable sequence (`ITERABLE_SEQUENCE`).
    - An iterable sequence is an ordered collection of elements that we can iterate over.
    - We are going to discuss iterable sequences based on three data types: Range, String, and Vector.
    - In the Simple Countdown example, the iterator variable (`countdown`) takes the values `1`, `2`, $\dots$, `10` of the iterable sequence `1:10`.

    for-loop: Deconstructing the Header¶
    for -loop:解构标头 ¶

    The for-loop statement has the following generic form.
    for -循环语句具有以下通用形式。

    for ITERATOR in ITERABLE_SEQUENCE
        BODY
    end
    • The header starts with the keyword for.
      标头以关键字 for 开头。
    • The keyword for is followed by an iterator variable (ITERATOR), the keyword in, and an iterable sequence (ITERABLE_SEQUENCE).
      关键字 for 后跟迭代器变量 ( ITERATOR )、关键字 in 和可迭代序列 ( ITERABLE_SEQUENCE )。
    • An iterable sequence is an ordered collection of elements that we can iterate over.
      可迭代序列是我们可以迭代的元素的有序集合。
      • We are going to discuss iterable sequences based on three data types: Range, String, and Vector.
        我们将讨论基于三种数据类型的可迭代序列:Range、String 和 Vector。
    • In the Simple Countdown example, the iterator variable (countdown) takes the values 1, 2, …, 10 of the iterable sequence 1:10.
      在简单倒计时示例中,迭代器变量 ( countdown ) 的值为 1 、 2 、 … 、 10
    [ ]:
    for i in 1:10
    println(i)
    end
    **Note:** We could also use `=` instead of the keyword `in`.

    Note: We could also use = instead of the keyword in.
    注意:我们还可以使用 = 代替关键字 in 。

    [ ]:
    for i = 1:10
    println(i)
    end
    ---
    ### `for`-loop: Iterable Sequences – Range

    - In the previous example, the iterable sequence is given by a **range**.
    - Mathematically, a *range* is sequence of elements uniquely determined by a combination of the following parameters.
    - `start`: the value of the *first* element in the sequence.
    - `step`: the *difference* (space) between two consecutive values in the sequence.
    - `stop`: (an upper bound on) the value of the *last* element in the sequence.
    - A generic range in Julia has the following form `start:step:stop`.
    - When the value of `step` is not specified, it is assumed to be `1`.
    In the following example, we use `start=1`, `step=3`, and `stop=10` $\implies$ iterable sequence elements are `1`, `1+3`, `1+3+3`, `1+3+3+3`.

    for-loop: Iterable Sequences – Range¶
    for -loop:可迭代序列 – 范围 ¶

    • In the previous example, the iterable sequence is given by a range.
      在前面的示例中,可迭代序列由范围给出。
    • Mathematically, a range is sequence of elements uniquely determined by a combination of the following parameters.
      从数学上讲,范围是由以下参数的组合唯一确定的元素序列。
      • start: the value of the first element in the sequence.
        start :序列中第一个元素的值。
      • step: the difference (space) between two consecutive values in the sequence.
        step :序列中两个连续值之间的差异(空格)。
      • stop: (an upper bound on) the value of the last element in the sequence.
        stop :序列中最后一个元素的值(上限)。
    • A generic range in Julia has the following form start:step:stop.
      Julia 中的通用范围具有以下形式 start:step:stop 。
      • When the value of step is not specified, it is assumed to be 1.
        当未指定 step 的值时,假定为 1 。

    In the following example, we use start=1, step=3, and stop=10 ⟹ iterable sequence elements are 1, 1+3, 1+3+3, 1+3+3+3.
    在下面的示例中,我们使用 start=1 、 step=3 和 stop=10 ⟹ 可迭代序列元素是 1 , 1+3 、 1+3+3 、 1+3+3+3 。

    [ ]:
    for i in 1:3:10
    println(i)
    end
    - Neither `start`, `step` nor `stop` have to be an *integer* value.
    • Neither start, step nor stop have to be an integer value.
      start 、 step 和 stop 都不必是整数值。
    [ ]:
    for i in 0.25:1:5
    println(i)
    end
    [ ]:
    for i in 0.25:0.5:5
    println(i)
    end
    [ ]:
    for i in 0.25:1:4.9999
    println(i)
    end
    - Neither `start`, `step` nor `stop` have to be a *positive* value.
    - Note that when `step < 0` the iterable sequence has a descending order. Furthermore, `step` can NOT be `0`.
    • Neither start, step nor stop have to be a positive value.
      start 、 step 和 stop 都不必是正值。
      • Note that when step < 0 the iterable sequence has a descending order. Furthermore, step can NOT be 0.
        请注意,当 step < 0 时,可迭代序列具有降序排列。此外, step 不能是 0 。
    [ ]:
    for i in -5:2.5:5
    println(i)
    end
    [ ]:
    for i in 10:-1:1
    println(i)
    end
    ### `for`-loop: Iterable Sequences – String

    - We can also use `String` values as iterable sequences.
    - In each iteration, the iterable variable takes the values of the different characters comprising the string.

    for-loop: Iterable Sequences – String¶
    for -loop:可迭代序列 – 字符串 ¶

    • We can also use String values as iterable sequences.
      我们还可以使用 String 值作为可迭代序列。
    • In each iteration, the iterable variable takes the values of the different characters comprising the string.
      在每次迭代中,可迭代变量采用组成字符串的不同字符的值。
    [ ]:
    for i in "Hello, world!"
    println(i)
    end
    ### `for`-loop: Iterable Sequences – Vector

    - We can also use `Vector` values as iterable sequences.
    - In each iteration, the iterable variable takes the values of the different elements in the vector.

    for-loop: Iterable Sequences – Vector¶
    for -loop:可迭代序列 – 向量 ¶

    • We can also use Vector values as iterable sequences.
      我们还可以使用 Vector 值作为可迭代序列。
    • In each iteration, the iterable variable takes the values of the different elements in the vector.
      在每次迭代中,可迭代变量采用向量中不同元素的值。
    [ ]:
    for i in [1, 2, 100, 200, 999]
    println(i)
    end
    ---
    ### `for`-loop: Nested

    We can nest multiple `for`-loops within one another.

    for-loop: Nested¶
    for -循环:嵌套 ¶

    We can nest multiple for-loops within one another.
    我们可以将多个 for 循环嵌套在一起。

    [ ]:
    suits = ["♠", "♦", "♥", "♣"] #[\spadesuit \:diamonds:, \:hearts:, \clubsuit]
    for suit in suits
    for rank in 1:13
    println("$suit $rank")
    end
    end
    ---
    ### Control Flow II: Conditional Execution

    Suppose we want to perform a countdown from `10` to `1` but only display the value of `countdown` when it is even.
    - Checking if a number *is even* is equivalent to checking if it is divisible by `2`.
    - We can use the modulus operator `%` which is a binary operator that gives the remainder of dividing two numbers.

    Control Flow II: Conditional Execution¶
    控制流 II:条件执行 ¶

    Suppose we want to perform a countdown from 10 to 1 but only display the value of countdown when it is even.
    假设我们要执行从 10 到 1 的倒计时,但仅在偶数时显示 countdown 的值。

    • Checking if a number is even is equivalent to checking if it is divisible by 2.
      检查一个数字是否为偶数相当于检查它是否可以被 2 整除。
    • We can use the modulus operator % which is a binary operator that gives the remainder of dividing two numbers.
      我们可以使用模运算符 % ,它是一个二元运算符,给出两个数字相除的余数。
    [ ]:
    println("3%1 = ", 3%1)
    println("4%2 = ", 4%2)
    println("5%3 = ", 5%3)
    - If a `x` is divisible by `y` $\implies$ `x % y = 0`.
    - To check if a number is even, we need to check if `x%2 == 0`.

    We know how to check if a number is even. But how do we tell just to only print `countdown` value *if* it is even?
    - To check *if* the value of countdown is even before printing it, we can use **conditional execution**.
    - Conditional execution provides the ability to check *if* certain conditions are met before executing the code.
    - The simplest form of conditional execution is an `if`-statement.
    • If a x is divisible by y ⟹ x % y = 0.
      如果 x 可以被 y ⟹ x % y = 0 整除。
    • To check if a number is even, we need to check if x%2 == 0.
      要检查数字是否为偶数,我们需要检查是否 x%2 == 0 。

    We know how to check if a number is even. But how do we tell just to only print countdown value if it is even?
    我们知道如何检查一个数字是否为偶数。但是我们如何告诉只打印 countdown 值(如果它是偶数)?

    • To check if the value of countdown is even before printing it, we can use conditional execution.
      要在打印之前检查倒计时的值是否为偶数,我们可以使用条件执行。
      • Conditional execution provides the ability to check if certain conditions are met before executing the code.
        条件执行提供了在执行代码之前检查是否满足某些条件的能力。
      • The simplest form of conditional execution is an if-statement.
        条件执行的最简单形式是 if 语句。
    [ ]:
    mod(10,2)
    [ ]:
    countdown = 10
    if countdown%2 == 0
    println("countdown is even.")
    end
    [ ]:
    countdown = 9
    if countdown%2 == 0
    println("countdown is even.")
    end
    Putting everything together:

    Putting everything together:
    将所有内容放在一起:

    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%2 == 0
    println(countdown)
    end
    countdown -= 1
    end
    ---
    ### Deconstructing the `if`-statement Header

    An `if`-statement has the following generic form:

    ```julia
    if BOOLEAN_EXPRESSION
    BODY
    end
    ```

    - The header consists of the keyword `if` followed by a Boolean expression (`BOOLEAN_EXPRESSION`).
    - The Boolean expression is the *condition* that determines whether the body of the statement is executed or not.
    - `BOOLEAN_EXPRESSION` is `true` $\;\; \implies$ `BODY` will be executed.
    - `BOOLEAN_EXPRESSION` is `false` $\implies$ `BODY` will NOT be executed.


    Deconstructing the if-statement Header¶
    解构 if 语句头 ¶

    An if-statement has the following generic form:
    if 语句具有以下通用形式:

    if BOOLEAN_EXPRESSION
        BODY
    end
    • The header consists of the keyword if followed by a Boolean expression (BOOLEAN_EXPRESSION).
      标头由关键字 if 后跟布尔表达式 ( BOOLEAN_EXPRESSION ) 组成。
    • The Boolean expression is the condition that determines whether the body of the statement is executed or not.
      布尔表达式是判断语句体是否执行的条件。
      • BOOLEAN_EXPRESSION is true ⟹ BODY will be executed.
        BOOLEAN_EXPRESSION 是 true ⟹ BODY 将被执行。
      • BOOLEAN_EXPRESSION is false ⟹ BODY will NOT be executed.
        BOOLEAN_EXPRESSION 是 false ⟹ BODY 将不会被执行。
    ----
    ### Alternative Conditional Execution

    - What if we would like to run something *else* if the condition not satisfied (i.e., when `BOOLEAN_EXPRESSION` evaluates to `false`)? For example:
    - Display the value of `countdown` if it is divisible by `3`.
    - Display a message stating that the number is not divisble by `3` and the remainder of the division.


    **Alternative execution** is a form of conditional execution with two possibilities (alternatives).
    - Each of the two possibilities is called a branch.
    - The condition (i.e., `BOOLEAN_EXPRESSION`) determines which of the two branches is executed.

    Alternative Conditional Execution¶
    替代条件执行 ¶

    • What if we would like to run something else if the condition not satisfied (i.e., when BOOLEAN_EXPRESSION evaluates to false)? For example:
      如果条件不满足(即,当 BOOLEAN_EXPRESSION 计算为 false 时),我们想运行其他东西怎么办?例如:
      • Display the value of countdown if it is divisible by 3.
        如果 countdown 能被 3 整除,则显示该值。
      • Display a message stating that the number is not divisble by 3 and the remainder of the division.
        显示一条消息,指出该数字不能被 3 和除法的余数整除。

    Alternative execution is a form of conditional execution with two possibilities (alternatives).
    替代执行是一种有两种可能性(替代方案)的条件执行形式。

    • Each of the two possibilities is called a branch.
      这两种可能性中的每一种都称为分支。
    • The condition (i.e., BOOLEAN_EXPRESSION) determines which of the two branches is executed.
      条件(即 BOOLEAN_EXPRESSION )确定执行两个分支中的哪一个。
    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%3 == 0
    println(countdown)
    else
    println("$countdown%3 = $(countdown%3) -> $countdown is not divisible by 3")
    end
    countdown -= 1
    end
    ----
    ### Chained Conditional Execution

    For more than two possibilities, we can use *chained conditional*.
    - Chained conditional statements can be created by using the keyword `elseif`.

    Chained Conditional Execution¶
    链式条件执行 ¶

    For more than two possibilities, we can use chained conditional.
    对于两种以上的可能性,我们可以使用链式条件。

    • Chained conditional statements can be created by using the keyword elseif.
      可以使用关键字 elseif 创建链式条件语句。
    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%3 == 0
    println("$countdown is divisible by 3")
    elseif countdown%2 == 0
    println("$countdown is divisible by 2")
    else
    println("$countdown is not divisible by 2 nor divisible by 3.")
    end
    countdown -= 1
    end
    - In chained conditional statements, conditions are checked in the following order:
    - If the condition in the first branch is `false`, the next branch is checked, and so on.
    - If the condition in any of the branches is `true`, the body in the corresponding branch is executed and the statement ends.
    - If more than one condition is `true`, only the first `true` branch is executed.
    • In chained conditional statements, conditions are checked in the following order:
      在链式条件语句中,按以下顺序检查条件:
      • If the condition in the first branch is false, the next branch is checked, and so on.
        如果第一个分支中的条件是 false ,则检查下一个分支,依此类推。
      • If the condition in any of the branches is true, the body in the corresponding branch is executed and the statement ends.
        如果任何分支中的条件为 true ,则执行相应分支中的主体并结束语句。
      • If more than one condition is true, only the first true branch is executed.
        如果 true 有多个条件,则仅执行第一个 true 分支。
    ----
    ### Nested Conditional Execution

    Another way to create a conditional execution statement with more than two possibilities (branches) is to use *nested conditional*.

    - Nested conditional statements can be created by nesting one branch of conditional execution into another.

    Nested Conditional Execution¶
    嵌套条件执行 ¶

    Another way to create a conditional execution statement with more than two possibilities (branches) is to use nested conditional.
    创建具有两种以上可能性(分支)的条件执行语句的另一种方法是使用嵌套条件。

    • Nested conditional statements can be created by nesting one branch of conditional execution into another.
      可以通过将条件执行的一个分支嵌套到另一分支来创建嵌套条件语句。
    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%3 == 0
    println("$countdown is divisible by 3")
    else
    if countdown%2 == 0
    println("$countdown is divisible by 2")
    else
    println("$countdown is not divisible by 2 nor divisible by 3.")
    end
    end
    countdown -= 1
    end
    ----
    ### Propositional Logic Truths Tables

    Each Boolean expression in the previous examples consists of *single* clause only (`countdown%2 == 0`, `countdown%3 == 0`, `...`).

    - What if we want to display the value of `countdown` if it is divisible by `2` **and** divisible by `3`?
    - What if we want to display the value of `countdown` if it is divisible by `2` **or** divisible by `3`?


    - In formal logic, we can change the meaning of a statement using the symbols:
    - ¬ $\equiv$ NOT
    - ∧ $\equiv$ AND
    - ∨ $\equiv$ OR


    - **Example:** Suppose that we have the following statements.
    - P = “The earth spins on its axis”.
    - Q = “The earth is round”.

    $\implies$
    - ¬P $\quad \equiv$ "The earth does **not** spin on its axis"

    Propositional Logic Truths Tables¶
    命题逻辑真值表 ¶

    Each Boolean expression in the previous examples consists of single clause only (countdown%2 == 0, countdown%3 == 0, ...).
    前面示例中的每个布尔表达式仅包含单个子句( countdown%2 == 0 、 countdown%3 == 0 、 ... )。

    • What if we want to display the value of countdown if it is divisible by 2 and divisible by 3?
      如果我们想要显示 countdown 的值,如果它可以被 2 整除并且可以被 3 整除,该怎么办?

    • What if we want to display the value of countdown if it is divisible by 2 or divisible by 3?
      如果我们想要显示 countdown 的值,如果它可以被 2 整除或可以被 3 整除,该怎么办?

    • In formal logic, we can change the meaning of a statement using the symbols:
      在形式逻辑中,我们可以使用符号改变语句的含义:

      • ¬ ≡ NOT ← ≡ 不是
      • ∧ ≡ AND ∧ ≡ 和
      • ∨ ≡ OR ∨ ≡ 或
    • Example: Suppose that we have the following statements.
      示例:假设我们有以下语句。

      • P = “The earth spins on its axis”.
        P =“地球绕其轴旋转”。
      • Q = “The earth is round”.
        Q =“地球是圆的”。

    ⟹

    • ¬P ≡ "The earth does not spin on its axis"
      ØP ≡ “地球不绕轴旋转”
    • P ∧ Q ≡ "The earth spins on its axis and The earth is round"
      P ∧ Q ≡ “地球绕其轴旋转,地球是圆的”
    • P ∨ Q ≡ "The earth spins on its axis or The earth is round"
      P ∨ Q ≡ “地球绕其轴旋转或地球是圆的”

    The truth table for ¬ (equivalently NOT)
    ← 的真值表(相当于 NOT)

    Q ¬P
    True 真的 False 错误的
    False 错误的 True 真的

    The truth table for ∧ (equivalently AND)
    ∧ 的真值表(相当于 AND)

    P Q P ∧ Q P∧Q
    True 真的 True 真的 True 真的
    True 真的 False 错误的 False 错误的
    False 错误的 True 真的 False 错误的
    False 错误的 False 错误的 False 错误的

    The truth table for ∨ (equivalently OR)
    ∨ 的真值表(相当于 OR)

    P Q P ∨ Q P∨Q
    True 真的 True 真的 True 真的
    True 真的 False 错误的 True 真的
    False 错误的 True 真的 True 真的
    False 错误的 False 错误的 False 错误的
    ----
    ### Logical Operators

    In Julia, the symbol for ¬ (NOT) is `!`, ∧ (AND) is `&&`, and ∨ (OR) is `||`.


    It is helpful to view `false` $\equiv$ `0` and `true` $\equiv$ `1`:<br>
    $\implies$ `!p` $\qquad \equiv$ `1-p`.<br>
    $\implies$ `p && q ` $\; \equiv$ `p * q`.<br>
    $\implies$ `p || q ` $\; \equiv$ `minimum(p+q, 1)`.



    The truth table for `!p`

    | `p` |`1-p` $\quad \equiv$ `!p` |
    |:------|:------|
    |`true` |`1-1=0` $\equiv$ `false`|
    |`false`|`1-0=1` $\equiv$ `true`|




    The truth table for `p&&q`

    | `p` | `q` |`p*q` $\quad \equiv$ `p&&q`|
    |:------|:------|:--------|
    |`true` |`true` |`1*1=1` $\equiv$ `true` |
    |`true` |`false`|`1*0=0` $\equiv$ `false`|

    Logical Operators¶ 逻辑运算符 ¶

    In Julia, the symbol for ¬ (NOT) is !, ∧ (AND) is &&, and ∨ (OR) is ||.
    在 Julia 中, Ø (NOT) 的符号是 ! ,∧ (AND) 是 && ,∨ (OR) 是 || 。

    It is helpful to view false ≡ 0 and true ≡ 1:
    查看 false ≡ 0 和 true ≡ 1 很有帮助:

    ⟹ !p ≡ 1-p.
    ⟹ p && q ≡ p * q.
    ⟹ p || q ≡ minimum(p+q, 1).

    The truth table for !p
    !p 的真值表

    p 1-p ≡ !p
    true 1-1=0 ≡ false
    false 1-0=1 ≡ true

    The truth table for p&&q
    p&&q 的真值表

    p q p*q ≡ p&&q
    true true 1*1=1 ≡ true
    true false 1*0=0 ≡ false
    false true 0*1=0 ≡ false
    false false 0*0=0 ≡ false

    The truth table for p||q
    p||q 的真值表

    p q minimum(p+q,1) ≡ p||q
    true true minimum(1+1,1)=1 ≡ true
    true false minimum(1+0,1)=1 ≡ true
    false true minimum(0+1,1)=1 ≡ true
    false false minimum(0+0,1)=0 ≡ false
    To display `countdown` only if it is divisible by `2` **and** divisible by `3` $\implies$ `countdown%2 == 0 && countdown%3 == 0`.

    To display countdown only if it is divisible by 2 and divisible by 3 ⟹ countdown%2 == 0 && countdown%3 == 0.
    仅当 countdown 可被 2 整除且可被 3 ⟹ countdown%2 == 0 && countdown%3 == 0 整除时才显示 countdown 。

    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%2 == 0 && countdown%3 == 0
    println(countdown)
    end
    countdown -= 1
    end
    To display `countdown` if it is divisible by `2` **or** divisible by `3` $\implies$ `countdown%2 == 0 || countdown%3 == 0`.

    To display countdown if it is divisible by 2 or divisible by 3 ⟹ countdown%2 == 0 || countdown%3 == 0.

    [ ]:
    countdown = 10
    while countdown > 0
    if countdown%2 == 0 || countdown%3 == 0
    println(countdown)
    end
    countdown -= 1
    end
    ---
    ### Summary: Looking Back and Looking Forward
    **Looking Back:**
    - The flow of execution is the order in which statements are executed.
    - We can control the flow of execution using the `while`-loop, `if`, `else`, and `elseif` statements.
    - The `while`-loop statement is used for evaluating certain expressions (usually with some variation), repeatedly, until a termination condition is reached.
    - In a `while`-loop, the termination condition is based on a *boolean expression*.
    - The termination condition of a `for`-loop is based on an `iterable sequence`.
    - An `iterable sequence` is an ordered collection of elements that we can iterate over, such as `Range`, `String`, and `Vector`.
    - The `if`, `else` and `elseif` statements are used to ensure that certain conditions are met before executing the code.
    - We can also control the flow of execution using the `for`-loop.

    Summary: Looking Back and Looking Forward¶

    Looking Back:

    • The flow of execution is the order in which statements are executed.
    • We can control the flow of execution using the while-loop, if, else, and elseif statements.
    • The while-loop statement is used for evaluating certain expressions (usually with some variation), repeatedly, until a termination condition is reached.
    • In a while-loop, the termination condition is based on a boolean expression.
    • The termination condition of a for-loop is based on an iterable sequence.
    • An iterable sequence is an ordered collection of elements that we can iterate over, such as Range, String, and Vector.
    • The if, else and elseif statements are used to ensure that certain conditions are met before executing the code.
    • We can also control the flow of execution using the for-loop.

    Looking Forward:

    • How can we group statements that makes our code easier to read and debug?
    • How can we eliminate repetitive code in a way that we can ensure that, later, when we make a change in the code, we only make the change in one place?
    [ ]:

    -

    Variables

    Callstack

      Breakpoints

      Source

      9
      1

      Kernel Sources

      Common Tools
      No metadata.
      Advanced Tools
      No metadata.
      ⌥ [
      ⌥ ]
      ⌥ ↘
      • Console
      • Change Kernel…
      • Clear Console Cells
      • Close and Shut Down…
      • Insert Line Break
      • Interrupt Kernel
      • New Console
      • Restart Kernel…
      • Run Cell (forced)
      • Run Cell (unforced)
      • Show All Kernel Activity
      • Debugger
      • Breakpoints on exception
      • Evaluate Code
        Evaluate Code
      • Next
        Next
        F10
      • Pause
        Pause
        F9
      • Step In
        Step In
        F11
      • Step Out
        Step Out
        ⇧ F11
      • Terminate
        Terminate
        ⇧ F9
      • Display Languages
      • English
        English
      • File Operations
      • Autosave Documents
      • Download
        Download the file to your computer
      • Reload Notebook from Disk
        Reload contents from disk
      • Revert Notebook to Checkpoint…
        Revert contents to previous checkpoint
      • Save Notebook
        Save and create checkpoint
        ⌘ S
      • Save Notebook As…
        Save with new path
        ⇧ ⌘ S
      • Trust HTML File
        Whether the HTML file is trusted. Trusting the file allows scripts to run in it, which may result in security risks. Only enable for files you trust.
      • Help
      • About Jupyter Notebook
      • Jupyter Reference
      • JupyterLab FAQ
      • JupyterLab Reference
      • Launch Jupyter Notebook File Browser
      • Markdown Reference
      • Show Keyboard Shortcuts
        Show relevant keyboard shortcuts for the current active widget
        ⇧ ⌘ H
      • Image Viewer
      • Flip image horizontally
        H
      • Flip image vertically
        V
      • Invert Colors
        I
      • Reset Image
        0
      • Rotate Clockwise
        ]
      • Rotate Counterclockwise
        [
      • Zoom In
        =
      • Zoom Out
        -
      • Kernel Operations
      • Shut Down All Kernels…
      • Main Area
      • Close All Other Tabs
      • Close Tab
        ⌥ W
      • Close Tabs to Right
      • End Search
        ⎋
      • Find Next
        ⌘ G
      • Find Previous
        ⇧ ⌘ G
      • Find…
        ⌘ F
      • Log Out
        Log out of JupyterLab
      • Search in Selection
        ⌥ L
      • Shut Down
        Shut down JupyterLab
      • Mode
      • Toggle Zen Mode
      • Notebook Cell Operations
      • Change to Code Cell Type
        Y
      • Change to Heading 1
        1
      • Change to Heading 2
        2
      • Change to Heading 3
        3
      • Change to Heading 4
        4
      • Change to Heading 5
        5
      • Change to Heading 6
        6
      • Change to Markdown Cell Type
        M
      • Change to Raw Cell Type
        R
      • Clear Cell Output
        Clear outputs for the selected cells
      • Collapse All Code
      • Collapse All Outputs
      • Collapse Selected Code
      • Collapse Selected Outputs
      • Copy Cell
        Copy this cell
        C
      • Cut Cell
        Cut this cell
        X
      • Delete Cell
        Delete this cell
        D, D
      • Disable Scrolling for Outputs
      • Enable Scrolling for Outputs
      • Expand All Code
      • Expand All Outputs
      • Expand Selected Code
      • Expand Selected Outputs
      • Extend Selection Above
        ⇧ K
      • Extend Selection Below
        ⇧ J
      • Extend Selection to Bottom
        ⇧ ↘
      • Extend Selection to Top
        ⇧ ↖
      • Insert Cell Above
        Insert a cell above
        A
      • Insert Cell Below
        Insert a cell below
        B
      • Insert Heading Above Current Heading
        ⇧ A
      • Insert Heading Below Current Heading
        ⇧ B
      • Merge Cell Above
        ⌃ ⌫
      • Merge Cell Below
        ⌃ ⇧ M
      • Merge Selected Cells
        ⇧ M
      • Move Cell Down
        Move this cell down
        ⌃ ⇧ ↓
      • Move Cell Up
        Move this cell up
        ⌃ ⇧ ↑
      • Paste Cell Above
        Paste this cell from the clipboard
      • Paste Cell and Replace
      • Paste Cell Below
        Paste this cell from the clipboard
        V
      • Redo Cell Operation
        ⇧ Z
      • Render Side-by-Side
        ⇧ R
      • Run Selected Cell
        Run this cell and advance
        ⇧ ⏎
      • Run Selected Cell and Do not Advance
        ⌘ ⏎
      • Run Selected Cell and Insert Below
        ⌥ ⏎
      • Run Selected Text or Current Line in Console
      • Select Cell Above
        K
      • Select Cell Below
        J
      • Select Heading Above or Collapse Heading
        ←
      • Select Heading Below or Expand Heading
        →
      • Set side-by-side ratio
      • Split Cell
        ⌃ ⇧ -
      • Undo Cell Operation
        Z
      • Notebook Operations
      • Access Next Kernel History Entry
        ⌥ ↓
      • Access Previous Kernel History Entry
        ⌥ ↑
      • Change Kernel…
      • Clear Outputs of All Cells
        Clear all outputs of all cells
      • Close and Shut Down Notebook
      • Collapse All Headings
        ⌃ ⇧ ←
      • Deselect All Cells
      • Edit Notebook Metadata
      • Enter Command Mode
        ⌃ M
      • Enter Edit Mode
        ⏎
      • Expand All Headings
        ⌃ ⇧ →
      • Interrupt Kernel
        Interrupt the kernel
      • New Console for Notebook
      • New Notebook
        Create a new notebook
      • Reconnect to Kernel
      • Render All Markdown Cells
      • Restart Kernel and Clear Outputs of All Cells…
        Restart the kernel and clear all outputs of all cells
      • Restart Kernel and Debug…
        Restart Kernel and Debug…
      • Restart Kernel and Run All Cells…
        Restart the kernel and run all cells
      • Restart Kernel and Run up to Selected Cell…
      • Restart Kernel…
        Restart the kernel
      • Run All Above Selected Cell
      • Run All Cells
        Run all cells
      • Run Selected Cell and All Below
      • Save and Export Notebook: Asciidoc
      • Save and Export Notebook: Executable Script
      • Save and Export Notebook: HTML
      • Save and Export Notebook: LaTeX
      • Save and Export Notebook: Markdown
      • Save and Export Notebook: PDF
      • Save and Export Notebook: Qtpdf
      • Save and Export Notebook: Qtpng
      • Save and Export Notebook: ReStructured Text
      • Save and Export Notebook: Reveal.js Slides
      • Save and Export Notebook: Webpdf
      • Select All Cells
        ⌘ A
      • Show Line Numbers
      • Toggle Collapse Notebook Heading
      • Trust Notebook
      • Other
      • Open in JupyterLab
        JupyterLab
      • Plugin Manager
      • Advanced Plugin Manager
      • Terminal
      • Decrease Terminal Font Size
      • Increase Terminal Font Size
      • New Terminal
        Start a new terminal session
      • Refresh Terminal
        Refresh the current terminal session
      • Use Terminal Theme: Dark
        Set the terminal theme
      • Use Terminal Theme: Inherit
        Set the terminal theme
      • Use Terminal Theme: Light
        Set the terminal theme
      • Text Editor
      • Decrease Font Size
      • Increase Font Size
      • New Julia File
        Create a new Julia file
      • New Markdown File
        Create a new markdown file
      • New Python File
        Create a new Python file
      • New Text File
        Create a new text file
      • Spaces: 1
      • Spaces: 2
      • Spaces: 4
      • Spaces: 4
      • Spaces: 8
      • Theme
      • Decrease Code Font Size
      • Decrease Content Font Size
      • Decrease UI Font Size
      • Increase Code Font Size
      • Increase Content Font Size
      • Increase UI Font Size
      • Set Preferred Dark Theme: JupyterLab Dark
      • Set Preferred Dark Theme: JupyterLab Light
      • Set Preferred Light Theme: JupyterLab Dark
      • Set Preferred Light Theme: JupyterLab Light
      • Synchronize Styling Theme with System Settings
      • Theme Scrollbars
      • Use Theme: JupyterLab Dark
      • Use Theme: JupyterLab Light
      • View
      • File Browser
      • Open JupyterLab
      • Show Debugger
        Show Show Debugger in the right sidebar
      • Show Header
      • Show Notebook Tools
        Show Show Notebook Tools in the right sidebar
      • Show Table of Contents
        Show Show Table of Contents in the left sidebar